[英]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.