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

标签 javascript node.js json request

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); 它返回

undefined

我从谁那里得到title的键值?

最佳答案

注意方括号 ([]) - 您有一个包含单个元素的数组。您首先需要为该元素下标,然后才访问该字段:

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

关于javascript - Node.JS:从 JSON 对象请求键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60020234/

相关文章:

javascript - Typescript 模块,需要外部 node_modules

json - Async.waterfall、foreach 和解析 JSON node.js。需要一些建议

python - 在Python中没有指针的情况下更新JOSNObject中的值

javascript - 为什么我在控制台中看到 Object.apply,而我无法在对象上使用它?

javascript - Node.js 数组实例化

javascript - onclick 触发调整大小,highcharts

java - 如何删除 Jackson 反序列化中的未知枚举键?

java - 默认情况下,Spring Data REST 从 JSON 中隐藏技术实体字段(@Version、@Id)。如何像往常一样归还它们?

javascript - 在javascript中使用变量动态引用html元素

php - Tinymce 没有出现