[英]Node.JS: Request a Key-Value from JSON Object
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);
在我的代码中它返回
不明确的
我从谁那里得到title的键值?
请注意方括号 ( []
) - 您有一个包含单个元素的数组。 您首先需要为该元素添加下标,然后才能访问该字段:
console.log(body.posts[0].title)
// Here --------------^
body.posts
是一个数组,因此您需要迭代元素以打印标题,例如:
for(let post of body.posts){
console.log(post.title);
}
你应该使用body.posts[0].title
。 在 json 中,方括号表示一个列表。 我希望它有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.