如何访问此JSON中的对象

时间:2017-04-21 22:31:35

标签: javascript json node.js

我目前正在使用命令行界面来显示随机引号,发现一个API来消耗引号,问题是JSON像这样返回一个数组

[{"ID":648,"title":"Jeff Croft","content":"<p>Do you validate other  <\/p>\n","link":"https:\/\/quotesondesign.com\/jeff-croft\/","custom_meta":{"Source":"<a href=\"http:\/\/cdharrison.com\/2009\/06\/notes-from-jeff-crofts-grids-css-standards-and-tomfoolery\/\">presentation<\/a>"}}]

我想要访问的是content<p>Do you validate other<\/p>这是我想要的引用

3 个答案:

答案 0 :(得分:2)

因此,假设您的json返回到变量RESULT:

var resultObj = JSON.parse(RESULT);
var theDataYouWant = resultObj[0].content;

内容现在位于theDataYouWant变量中。

答案 1 :(得分:1)

由于这是一个JSON对象数组,您可以通过

访问它

&#13;
&#13;
    var data = [
      {
        "ID": 648,
        "title": "Jeff Croft",
        "content": "<p>Do you validate other  <\/p>\n",
        "link": "https:\/\/quotesondesign.com\/jeff-croft\/",
        "custom_meta": {
          "Source": "<a href=\"http:\/\/cdharrison.com\/2009\/06\/notes-from-jeff-crofts-grids-css-standards-and-tomfoolery\/\">presentation<\/a>"
        }
      }
    ];
    for(var i = 0; i < data.length; i++) {
        console.log(data[i].content);
    }
&#13;
&#13;
&#13;

答案 2 :(得分:1)

var A = [{"ID":648,"title":"Jeff Croft","content":"<p>Do you validate other  <\/p>\n","link":"https:\/\/quotesondesign.com\/jeff-croft\/","custom_meta":{"Source":"<a href=\"http:\/\/cdharrison.com\/2009\/06\/notes-from-jeff-crofts-grids-css-standards-and-tomfoolery\/\">presentation<\/a>"}}]

A.map(a => a.content)
//gives: ["<p>Do you validate other  </p>"]

我喜欢这种方法,因为你的json可能很大,你可能想要所有的内容项。

但是如果你只想要第一个,你可以随时解构(es6):

const [first] = A.map(a => a.content)
first; // gives => "<p>Do you validate other  </p>"

当然,我假设超过&#34;一个&#34;数据集。您可以随时使用[0]获取第一个项目(就像本文中提到的其他项目一样)

A.map(a => a.content)[0]
//gives: "<p>Do you validate other  </p>"
相关问题