How to select specific field of a JSON response in Node JS?

Viewed 46

I have the following API response named "body" and trying to log a specific field/submap, for example the "response" map. I don't really know the correct syntax in NodeJS or JavaScript.

{"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}}},]}

The code is below:

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);
});

I tried console.log(body.response); without success. I also tried body["response"] ending with "undefined" result.

2 Answers

It seems body was a String result so I could select the field with JSON syntax. I solved with console.log(JSON.parse(body).response[0]);

Two approaches:

Approach 1: Set the Content-Type as application/json in the server.

Approach 2: Convert the body from string to JSON object by JSON.parse

Related