0

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!

1 Answer 1

2

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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah! Sorry about the noob question, I'm new to this. What if I have an array inside of this array? Like this: { "address": "{\"cep\":\"30410-600\",\"city\":\"Belo Horizonte\"}"},? I need to use the position on the "adress" too, isn't?
If your data is inside curly braces - it is an object. If your data is inside square brackets - it is an array. You don't need to use the index on the "address" because it has an object - use address.city e.g.
In case it answers your question, please mark it as answered. There is a checkbox to the left from the answer. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.