Vinicius Mocci
Vinicius Mocci

Reputation: 99

Get single key value from JSON with Node

I'm using a RESTFUL API to get some JSON data, this is the code:

const request= require('request');

const options = { 
    url: 'https://myurl.com/',
    headers: {
        'x-functions-key': 'mykey'
    }
};

request.get(options, (err, response, body) =>{
    if(err){
        console.log("Error!")
    }

    const obj = JSON.parse(body);

    //console.log(obj.id);
    console.log(body);

});

This is the response from console.log if I only use the body parameter:

{
    "id": "19678u36-au71-4112-0057-950jjkca61d1",
    "phone": "",
    "address": "{\"cep\":\"00000-000\",\"city\":\"Belo Horizonte\",\"state\":\"MG\",\"country\":\"Brasil\",\"street\":\"My Street\",\"district\":\"My District\",\"number\":\"000\",\"complement\":\"000\"}",
    "items": "{\"tax\":12,\"amount\":2,\"items\":[{\"type\":\"NILO\",\"name\":\"Nilo Zack\",\"quantity\":1}]}",
    "userEmail": "[email protected]",
    "userData": "{\"name\":\"User Name\",\"document\":\"000.000.000-00\",\"phone\":\"\",\"email\":\"[email protected]\"}",
    "order": "{\"tid\":\"ch_5PXxuyoqw4\",\"notes\":\"XQ22ARP\",\"status\":2}",
    "createdAt": "2020-05-05T17:50:45.707Z",
    "updatedAt": "2020-05-05T17:50:45.708Z"
  },

I want to print only the id key, but when I run the console.log(obj.id) I get an undefined response from the console. Any ideas? Maybe I'm not parsing correctly the JSON data, dunno. Thanks for any help!

Upvotes: 0

Views: 1685

Answers (1)

Eugene Obrezkov
Eugene Obrezkov

Reputation: 2986

Based on the fact that there is a , in your body, I assume that response is not an object, but an array.

request.get(options, (err, response, body) => {
    if (err) {
        console.log("Error!")
    }

    const items = JSON.parse(body);
    console.log(items[0].id);
});

Upvotes: 2

Related Questions