You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Postman中提取GraphQL响应并转换为指定films数组格式?

问题

我从Starwar的GraphQL接口获取数据,请求体如下:

query {
  allFilms {
    films {
      title
    }
  }
}

当前得到的响应数据是:

{
    "data": {
        "allFilms": {
            "films": [
                {
                    "title": "A New Hope"
                },
                {
                    "title": "The Empire Strikes Back"
                },
                {
                    "title": "Return of the Jedi"
                },
                {
                    "title": "The Phantom Menace"
                },
                {
                    "title": "Attack of the Clones"
                },
                {
                    "title": "Revenge of the Sith"
                }
            ]
        }
    }
}

但我希望把响应转换成仅包含films的数组格式,如下:

[
  {
    "title": "A New Hope"
  },
  {
    "title": "The Empire Strikes Back"
  },
  {
    "title": "Return of the Jedi"
  },
  {
    "title": "The Phantom Menace"
  },
  {
    "title": "Attack of the Clones"
  },
  {
    "title": "Revenge of the Sith"
  }
]

请问该如何实现?我猜测这和Pre-request Script相关。

实现方法

你猜的方向有偏差,处理响应格式需要用Tests脚本(请求后执行),Pre-request Script是在发送请求前运行的,没法修改返回的响应。具体操作如下:

  1. 在请求的「Tests」标签页中,输入以下JavaScript代码:
// 解析原始响应的JSON数据
const rawResponse = pm.response.json();
// 逐层提取目标films数组
const targetFilms = rawResponse.data.allFilms.films;
// 替换响应体为提取后的数组
pm.response.setBody(targetFilms);
  1. 重新发送请求后,就能在「Response」标签页看到仅包含films数组的格式了。

这段代码逻辑很直接:先解析原始响应数据,取出嵌套的films数组,再用pm.response.setBody()替换原始响应体,最终得到你需要的输出格式。

内容的提问来源于stack exchange,提问作者Kel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:51:33