Kayode Adeola
Kayode Adeola

Reputation: 45

How can I access Objects in this JSON

I'm currently working on a command line interface to show random quotes, found an API to consume quotes from, problem is the JSON is returned as an array like this

[{"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>"}}]

What I want to access is the content:<p>Do you validate other<\/p> which is the quote I want

Upvotes: 1

Views: 72

Answers (3)

james emanon
james emanon

Reputation: 11837

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

I like this approach because your json could be huge, and you might want all of the content items.

but if you want just the first one, you can always destructure (es6):

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

of course, I'm assuming more than "one" data set. You can always use the [0] to get the first item (like others alluded in this post)

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

Upvotes: 1

Zanko
Zanko

Reputation: 4694

Since this is a Array of JSON objects you can access it by

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

Upvotes: 1

Ken
Ken

Reputation: 466

So lets assume your json is returned into a variable RESULT:

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

The content is now in the theDataYouWant variable.

Upvotes: 2

Related Questions