froggomad
froggomad

Reputation: 1915

Can't iterate through JSON object

I'm pulling a JSON request from the politifact API:

request('http://politifact.com/api/v/2/statement/?format=[JSON]&order_by=-ruling_date&limit=1')
        .then(({
            data
        }) => {        
        newArticles = extractListingsFromJSON(data); 

and parsing it with a function that the JSON is passed to

function extractListingsFromJSON(json) {    
    var jsonObject = json.objects    

Outputs entire objects array

var headline = jsonObject[0].facebook_headline
console.log("headline:\n" + headline)

Outputs headline from Objects[0]

This works as intended. However, when I try to iterate through the objects array like so:

for (var attr in jsonObject) {
    console.log(attr+": "+jsonObject.facebook_headline);
}   

Outputs "0: undefined"

I also tried:

console.log(attr+": "+jsonObject[facebook_headline];

Outputs nothing

Upvotes: 0

Views: 461

Answers (2)

DimosthenisK
DimosthenisK

Reputation: 61

You still need the attr key to iterate through the jsonObject. Try doing attr+" :"+jsonObject[attr].facebook_headline instead.

Upvotes: 1

ralphtheninja
ralphtheninja

Reputation: 133008

As you mentioned yourself jsonObject is an array.

json.objects.forEach(function (i) {
  console.log(i.facebook_headline)
})

Upvotes: 3

Related Questions