Tony Thompson
Tony Thompson

Reputation: 3

reading nested JSON using JavaScript

I'm trying to read the nested content of a JSON file using JavaScript.

Here is my JavaScript:

<script>
var obj, xmlhttp, myObj, x, txt = "";
var request = new XMLHttpRequest();
request.open('GET', 'https://private-c01be-moneyadviceservice.apiary-mock.com/locale/categories.json');
request.setRequestHeader("Content-type", "application/json");
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);

  myObj = JSON.parse(this.responseText);

   for (x in myObj) {
        txt += "<h2>" + myObj[x].title + "</h2><p>" + myObj[x].description + "</p><br/>";
        txt += "<h3>" + myObj[x].contents.title + "</h3><p>" + myObj[x].contents.description + "</p><br/>";
    }

    document.getElementById("MAS").innerHTML = txt; 
  }
};

request.send();
</script>

And here is the JSON file:

 {
    "id": "life-events",
    "type": "category",
    "title": "Life events",
    "description": "When big things happen - having a baby, losing your job, getting divorced or retiring\n - it helps to be in control of your money\n",
    "contents": [
        {
            "id": "setting-up-home",
            "type": "category",
            "title": "Setting up home",
            "description": "Deciding whether to rent or buy, working out what you can afford and managing\n money when sharing with others\n",
            "contents": [
            ]
        },
        {
            "id": "young-people-and-money",
            "type": "category",
            "title": "Leaving school or college",
            "description": "",
            "contents": [
            ]
        },
        {
            "id": "having-a-baby",
            "type": "category",
            "title": "Having a baby",
            "description": "",
            "contents": [
            ]
        }
    ]
},

The nested JSON is showing as 'Undefined'. How do I access the nested data?

I've read countless posts about this topic but none have really helped in this instance

Upvotes: 0

Views: 762

Answers (2)

Lotus91
Lotus91

Reputation: 1125

You need to loop over the contents as well because they are arrays like below :

   for (x in myObj) {
     txt += "<h2>" + myObj[x].title + "</h2><p>" + myObj[x].description + "</p><br/>";
     for(y in myObj[x].contents){
    txt += "<h3>" + myObj[x].contents[y].title + "</h3><p>" + myObj[x].contents[y].description + "</p><br/>";
     }
   }

Here is a JSBin.

Upvotes: 2

Master Po
Master Po

Reputation: 1697

You can't access myObj[x].contents.title since contents is an array. Need to iterate myObj[x].contents for it's properties.

Upvotes: 1

Related Questions