通过HTTP请求调用GraphQL接口后,无法遍历JSON响应数据
GraphQL接口数据提取问题
我通过HTTP请求调用GraphQL接口,已成功获取包含所需数据的响应,但无法导航数据以提取所需字段。
第一次尝试代码
const query = JSON.stringify({query: '{' + ' all_insight_article('+ ' locale: "en-gb"'+ ' where: {business_unit: {business_unit: {title: "Some Brand"}, MATCH: ALL}, audience: {MATCH: ALL, audiences: {title: "Management"}}publish_date_gt: "2023-02-01"}'+ ' ) {items {'+ ' audienceConnection {'+ ' edges {'+ ' node {... on Audiences {title system {uid}}}}}'+ ' system {'+ ' uid'+ ' publish_details {time}'+ ' updated_at}'+ ' absolute_url'+ ' title'+ ' subtitle'+ ' main_image'+ ' topicsConnection {'+ ' edges {'+ ' node {'+ ' ... on Topics {'+ ' title'+ ' display_name'+ ' system {uid}}}}}}total}}' }); var req = new HttpClientRequest("https://eu-graphql.contentstack.com/stacks/bltcxxx?environment=xxx&access_token=xxx") req.header["Content-Type"] = "application/json" req.method = "POST" req.body = query req.execute() var response = req.response; var posts = JSON.parse(response.body); var articleList_json = []; var i for ( i = 0; i < 15; i++) { articleList_json.push({ "title": posts[i].title, }); } logInfo(articleList_json);
运行时报错:posts is undefined.
注:HttpClientRequest为所用应用的类,功能近似标准HTTP请求。
第二次尝试代码(问题仍未解决)
var response = req.response; var posts = JSON.stringify(response.body); var articleList_json = []; var i for ( i = 0; i < 15; i++) { var graphQLJSON = JSON.parse(posts[i]); articleList_json.push({ "title": graphQLJSON.data.title, }); } logInfo(articleList_json);
问题分析与修正方案
错误原因
- 第一次代码中,GraphQL响应为标准结构
{ data: {...}, errors: [...] },直接用posts[i]访问会报错——posts是对象而非数组,且若解析失败或响应为空会导致posts未定义。 - 第二次代码中,
JSON.stringify(response.body)属于冗余操作(response.body已是字符串),posts[i]取的是字符串单个字符,无法解析为有效JSON;且graphQLJSON.data.title路径错误,标题字段位于data.all_insight_article.items数组的每个元素中。
修正后的代码
const query = JSON.stringify({query: '{' + ' all_insight_article('+ ' locale: "en-gb"'+ ' where: {business_unit: {business_unit: {title: "Some Brand"}, MATCH: ALL}, audience: {MATCH: ALL, audiences: {title: "Management"}}publish_date_gt: "2023-02-01"}'+ ' ) {items {'+ ' audienceConnection {'+ ' edges {'+ ' node {... on Audiences {title system {uid}}}}}'+ ' system {'+ ' uid'+ ' publish_details {time}'+ ' updated_at}'+ ' absolute_url'+ ' title'+ ' subtitle'+ ' main_image'+ ' topicsConnection {'+ ' edges {'+ ' node {'+ ' ... on Topics {'+ ' title'+ ' display_name'+ ' system {uid}}}}}}total}}' }); var req = new HttpClientRequest("https://eu-graphql.contentstack.com/stacks/bltcxxx?environment=xxx&access_token=xxx") req.header["Content-Type"] = "application/json" req.method = "POST" req.body = query req.execute() var response = req.response; // 处理响应并提取数据 if (response && response.body) { try { const graphQLResponse = JSON.parse(response.body); // 检查GraphQL请求是否返回错误 if (graphQLResponse.errors) { logInfo("GraphQL请求错误: " + JSON.stringify(graphQLResponse.errors)); } else { // 从响应结构中获取文章数组 const articles = graphQLResponse.data?.all_insight_article?.items || []; const articleList_json = []; // 遍历文章,最多取15条避免越界 for (let i = 0; i < Math.min(articles.length, 15); i++) { articleList_json.push({ "title": articles[i].title, // 可按需添加其他字段 "absolute_url": articles[i].absolute_url }); } logInfo(articleList_json); } } catch (parseError) { logInfo("响应解析失败: " + parseError.message); } } else { logInfo("未获取到有效响应"); }
关键修正点
- 按照GraphQL响应结构,通过
graphQLResponse.data.all_insight_article.items获取目标文章数组,匹配查询的层级结构 - 增加异常处理,覆盖响应为空、解析失败、GraphQL返回错误等场景
- 遍历数组时取实际长度与15的最小值,避免数组越界
内容的提问来源于stack exchange,提问作者David Garcia
相关产品推荐
相关产品推荐

