nurul98
nurul98

Reputation: 117

Creating html elements through nested JSON objects

So I've managed to successfully create HTML elements through JSON objects before, but now that I've changed my JSON objects to nested JSON, I am not able to reproduce the HTML elements accordingly. I am pretty new to programming so can anyone help me find out where I have gone wrong?

JSON File:

{  
  "ThreeG": [
    {
        "title":"Testing 1",
        "filePath":"https://example.com",
        "imagePath":"images/test.jpg"
    },
    {
        "title":"Testing 2",
        "filePath":"https://example.com",
        "imagePath":"images/test2.jpg"
    }
   ]
}

Script:

<script>
    $.ajax({
      url : "TestFiles.json",
      type : "post", 
      contentType:"application/json",
      success : function(list){           
          var divCol  = "<div class='col-md-offset-1 col-sm-5 col-md-5'>";
          var divWell = "<div class='well' style='position:relative'>";
          var divClose= "</div>";

          list.forEach(function(obj, index) {

            var title     = "<h4>"      + obj.ThreeG.title    + "</h4>";
            var linkStart = "<a href='" + obj.ThreeG.filePath + "' target='_blank'>" ;
            var image     = "<img data-toggle='tooltip' data-placement='left' title='Click to open data' src='" + obj.ThreeG.imagePath + "' height='100%' width='100%'/>"
            var linkEnd   =  "</a>";

            var div = divCol    +
            divWell     +
            title       +
            linkStart       +
            image       +
            linkEnd +
            divClose +
            divClose;

            console.log(obj);
           $("#test").append(div); 

           })
        }
    });
  </script>

Upvotes: 0

Views: 451

Answers (2)

Pankaj Shukla
Pankaj Shukla

Reputation: 2672

var obj = {  
  "ThreeG": [
    {
        "title":"Testing 1",
        "filePath":"https://example.com",
        "imagePath":"images/test.jpg"
    },
    {
        "title":"Testing 2",
        "filePath":"https://example.com",
        "imagePath":"images/test2.jpg"
    }
   ]
};

for(var i=0;i<obj.ThreeG.length;i++) {
var data = obj.ThreeG[i];//Take a reference here
console.log(data.title, data.filePath, data.imagePath);
}

You cannot say obj.ThreeG.title since obj.ThreeG is an array. You need to use obj.ThreeG[0].title and obj.ThreeG[1].title etc.

Do some looping as shown above.

Upvotes: 0

riyaz-ali
riyaz-ali

Reputation: 9034

The list param in the success callback is an object with property / key ThreeG. So instead of list.forEach, you should do list.ThreeG.forEach, then each obj in the forEach callback will be the json object that you can use to create HTML elements.

list.ThreeG.forEach(function(obj, index) {
         console.log(obj); // { "title":"Testing 1", "filePath":"https://example.com", "imagePath":"images/test.jpg" } for the first object
}

Upvotes: 1

Related Questions