Monday, July 23, 2018

How to Convert JSON Data Into HTML

Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually.

How to Convert JSON Data Into HTML

The purpose of the code is to generate html by using key and corresponding  value.

var json = [  
   {  
      "id":0,
      "imageLink":"https://s3.amazonaws.com/freecodecamp/funny-cat.jpg",
      "altText":"A white cat wearing a green helmet shaped melon on it's head. ",
      "codeNames":[  
         "Juggernaut",
         "Mrs. Wallace",
         "Buttercup"
      ]
   },
   {  
      "id":1,
      "imageLink":"https://s3.amazonaws.com/freecodecamp/grumpy-cat.jpg",
      "altText":"A white cat with blue eys, looking very grumpy. ",
      "codeNames":[  
         "Oscar",
         "Scrooge",
         "Tyrion"
      ]
   },
   {  
      "id":2,
      "imageLink":"https://s3.amazonaws.com/freecodecamp/mischievous-cat.jpg",
      "altText":"A ginger cat with one eye closed and mouth in a grin-like expression. Looking very mischievous. ",
      "codeNames":[  
         "The Doctor",
         "Loki",
         "Joker"
      ]
   }
]
var html = "";
//iterating through all the item one by one.
json.forEach(function(val) {
  //getting all the keys in val (current array item)
  var keys = Object.keys(val);
  //assigning HTML string to the variable html
  html += "<div class = 'cat'>";
  //iterating through all the keys presented in val (current array item)
  keys.forEach(function(key) {
    //appending more HTML string with key and value aginst that key;
    html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
  });
  //final HTML sting is appending to close the DIV element.
  html += "</div><br>";
});

document.body.innerHTML = html;


Src:
https://stackoverflow.com/questions/48124586/how-to-convert-json-data-into-html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

0 Comments

Post a Comment