ahmed khattab
ahmed khattab

Reputation: 2501

parsing JSON data with java script

I use Google plus API and get this data from it and get an error while parsing this JSON data

first part of json data that i parsing

enter image description here

and here is the code I use to parse this data and get error as data object is tested and work fine and hold data as it appear in past 2 images

var allIems = data.items;
for (var element in allIems) {
  document.getElementById('datafromapi').innerHTML +=
    (" , published time :" + element.published +
      " , last updated time :" + element.updated +
      ", complete url : " + element.url

    );
  var obj = element.object.attachments;

  document.getElementById('datafromapi').innerHTML +=
    (+"\nattachments of post :\n" +
      " type : " +
      obj[0].objectType +
      " ,displayName of content : " +
      obj[0].displayName +
      " ,content URL  : " +
      obj[0].url +
      " ,content data :" +
      obj[0].image.url +
      " ,content type : " +
      obj[0].image.type +
      " ,content height : " +
      obj[0].image.height +
      " ,content width : " +
      obj[0].image.width +
      "\n\n\n");


}
});

i got that error appear

Uncaught TypeError: Cannot read property 'attachments' of undefined

Upvotes: 1

Views: 592

Answers (2)

Jordankid93
Jordankid93

Reputation: 73

Javascript has a built in JSON parser you can use that takes in a string of the data and returns an object.

let jsonDataAsString = "{\"a\":1,\"b\":2}";

let jsonDataAsObject = JSON.parse(jsonDataAsString);

Then you can traverse through the data as an object, referencing properties using dot-notation

console.log(jsonDataAsObject.a); // 1

To be safe, you should be comparing properties to null before trying to use then

if(jsonDataAsObject.somePropery != null) {
    // the property exists so you can access it here
}

Upvotes: 1

Igor
Igor

Reputation: 15893

element values in

for (var element in allIems) {

are keys of allItems, which in this case are array indices. You have to address the actual array items like this:

var obj = allItems[element].object.attachments;

Your code element.object.attachments; tries to access property object of a number, which does not exist.

Since we know that allItems is an array, you could have written:

for (var i = 0; i < allIems.length; i++) {
  var obj = allItems[i].object.attachments;

Upvotes: 1

Related Questions