簡體   English   中英

如何在此JSON中訪問對象

[英]How can I access Objects in this JSON

我目前正在命令行界面上顯示隨機引號,找到了一個使用引號的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>這是我想要的報價

因此,假設您的json返回到變量RESULT中:

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

內容現在位於theDataYouWant變量中。

由於這是一個JSON對象數組,因此您可以通過

  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); } 

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>"

當然,我假設的數據集不止一個。 您總是可以使用[0]來獲得第一項(就像本文中提到的其他項一樣)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM