Node.JS:从JSON对象请求键值

问题描述 投票:0回答:2

API_URL显示如下内容:

{
    "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);

});

返回我

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

如果我在代码中尝试console.log(body.posts.title);,它将返回

未定义

谁获得标题的键值?

javascript node.js json request
2个回答
2
投票

请注意方括号([])-您拥有带有单个元素的array。您首先需要为该元素添加下标,然后才可以访问该字段:

console.log(body.posts[0].title)
// Here --------------^

1
投票

body.posts是一个数组,因此您需要迭代元素以打印标题,例如:

for(let post of body.posts){
    console.log(post.title);
}
© www.soinside.com 2019 - 2024. All rights reserved.