【问题标题】:Node.JS: Request a Key-Value from JSON ObjectNode.JS:从 JSON 对象请求键值
【发布时间】:2020-05-18 02:06:41
【问题描述】:

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的keyvalue是谁获取的?

【问题讨论】:

    标签: javascript node.js json request


    【解决方案1】:

    注意方括号 ([]) - 你有一个带有单个元素的 array。您首先需要下标该元素,然后才能访问该字段:

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

    【讨论】:

      【解决方案2】:

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

      for(let post of body.posts){
          console.log(post.title);
      }
      

      【讨论】:

        【解决方案3】:

        您应该使用body.posts[0].title。在 json 中,方括号表示一个列表。希望对你有帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-10-02
          • 2014-11-11
          • 1970-01-01
          • 1970-01-01
          • 2012-01-28
          • 2014-09-13
          相关资源
          最近更新 更多