如何在Node.js中选取JSON响应的指定字段?
问题:无法访问API响应中的response字段
我用Node.js的request库调用足球API,拿到的响应body里明明包含response字段,但用console.log(body.response)或body["response"]都返回undefined。
API响应示例:
{"get":"fixtures","parameters":{"league":"135","season":"2022","status":"NS","timezone":"Europe/rome"},"errors":[],"results":40,"paging":{"current":1,"total":1},"response":[{"fixture":{"id":881790,"referee":"M. Piccinini","timezone":"Europe/rome","date":"2022-08-20T18:30:00+02:00","timestamp":1661013000,"periods":{"first":null,"second":null},"venue":{"id":943,"name":"Stadio Olimpico Grande Torino","city":"Torino"},"status":{"long":"Not Started","short":"NS","elapsed":null}},"league":{"id":135,"name":"Serie A","country":"Italy","logo":"https://media.api-sports.io/football/leagues/135.png","flag":"https://media.api-sports.io/flags/it.svg","season":2022,"round":"Regular Season - 2"},"teams":{"home":{"id":503,"name":"Torino","logo":"https://media.api-sports.io/football/teams/503.png","winner":null},"away":{"id":487,"name":"Lazio","logo":"https://media.api-sports.io/football/teams/487.png","winner":null}},"goals":{"home":null,"away":null},"score":{"halftime":{"home":null,"away":null},"fulltime":{"home":null,"away":null},"extratime":{"home":null,"away":null},"penalty":{"home":null,"away":null}}},]}
我的Node.js代码:
var request = require("request"); var options = { method: 'GET', url: 'https://v3.football.api-sports.io/fixtures?league=135&season=2022&status=NS&timezone=Europe/rome', qs: {}, headers: { 'x-rapidapi-host': 'v3.football.api-sports.io', 'x-rapidapi-key': 'xxxxxxxxxxxxxxxxx' } }; request(options, function (error, response, body) { if (error) throw new Error(error); console.log(body); });
解决方法
问题核心是request库默认返回的body是字符串类型,不是可直接访问属性的JSON对象,所以直接用点语法或方括号语法访问字段会得到undefined。有两种可行的解决方式:
方法1:手动解析JSON字符串
在回调函数中使用JSON.parse()将字符串格式的body转换成JSON对象:
request(options, function (error, response, body) { if (error) throw new Error(error); // 解析字符串为JSON对象 const parsedBody = JSON.parse(body); // 正常访问response字段 console.log(parsedBody.response); });
方法2:让request自动解析JSON
在请求配置选项中添加json: true,request会自动将响应内容解析为JSON对象返回:
var options = { method: 'GET', url: 'https://v3.football.api-sports.io/fixtures?league=135&season=2022&status=NS&timezone=Europe/rome', qs: {}, headers: { 'x-rapidapi-host': 'v3.football.api-sports.io', 'x-rapidapi-key': 'xxxxxxxxxxxxxxxxx' }, // 开启自动JSON解析 json: true }; request(options, function (error, response, body) { if (error) throw new Error(error); // 此时body已是JSON对象,直接访问字段 console.log(body.response); });
内容的提问来源于stack exchange,提问作者faccio
相关产品推荐
相关产品推荐

