2

API_URL show something like this:

{
    "posts": [{
        "id": "987f2bhfzu3r3f43fg",
        "uuid": "g3g4g-4g34gd7f-40ae-96g43g82-65g34g43ccec94a566",
        "title": "This is my title",
        "tag": "thistag"
    }]
}
const request = require('request');


request('API_URL', { json: true }, (err, res, body) => {
  if (err) { return console.log(err); }
  console.log(body.posts);

});

Returns me

[{
    "id": "987f2bhfzu3r3f43fg",
    "uuid": "g3g4g-4g34gd7f-40ae-96g43g82-65g34g43ccec94a566",
    "title": "This is my title",
    "tag": "thistag"
}]

If I try console.log(body.posts.title); in my code it returns

undefined

Who do I get the keyvalue of title?

0

3 Answers 3

3

Note the square brackets ([]) - you have got an array with a single element. You first need to subscript that element, and only then access the field:

console.log(body.posts[0].title)
// Here --------------^
Sign up to request clarification or add additional context in comments.

Comments

2

body.posts is an array so you need to iterate the elements to print the title like:

for(let post of body.posts){
    console.log(post.title);
}

Comments

2

You should use body.posts[0].title. In json the square brackets indicate a list. I hope it helps.

Comments

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.