[英]Node.JS: Request a Key-Value from JSON Object
API_URL show something like this: 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);
});
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);
如果我尝试
console.log(body.posts.title);
in my code it returns在我的代码中它返回
undefined
不明确的
Who do I get the keyvalue of title ?我从谁那里得到title的键值?
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 --------------^
body.posts
is an array so you need to iterate the elements to print the title like: body.posts
是一个数组,因此您需要迭代元素以打印标题,例如:
for(let post of body.posts){
console.log(post.title);
}
You should use body.posts[0].title
.你应该使用
body.posts[0].title
。 In json the square brackets indicate a list.在 json 中,方括号表示一个列表。 I hope it helps.
我希望它有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.