corry
corry

Reputation: 1529

Get specific fields in JSON

I have a problem with getting some JSON fields in NodeJS. Here is my JSON structure:

{
    "header":
    {
        "file1":0,
        "file2":1,
        "subfiles":{
          "subfile1":"true",
          "subfile2":"true",
        }
    },

    "response":
    {
        "number":678,
        "start":0,
        "docs":[
            {
                "id":"d3f3d",
                "code":"l876s",
                "country_name":"United States",
                "city":"LA"
            },
            {
                "id":"d2f2d",
                "code":"2343g",
                "country_name":"UK",
                "city":"London"
            }
        ]
    }
}

How to access to specific fields (id, city or country_name) in structure like this? I'm trying something in NodeJS, but I cannot get specific fields.

request('http://url.com', function (error, res, body) {
  if (!error && res.statusCode == 200) {
    console.log(body) 
  }

    res.on('data', function(chunk){
        body += chunk;
    });

    res.on('end', function(){
        var urlResponse = JSON.parse(body);
        console.log("Got a response: ", urlResponse.response.docs.city);
    });
});

Upvotes: 0

Views: 3602

Answers (2)

Josh
Josh

Reputation: 694

Try using using a data variable to accumulate your chunks and then data.toString() to force the buffered content to string, which will be parseable JSON.

Additionally, you need to access the specific member of the docs array.

Upvotes: 1

Adam Paulukanis
Adam Paulukanis

Reputation: 21

Have you tried something like this:

thatObject.response.docs.forEach((element) => { console.log( element.id ); });

?

property docks is an array, so you can use functions: forEach, or for, or whatever you wish

Upvotes: 1

Related Questions