Parsing JSON with Javascript

When I have to, sometimes I have trouble with forgetting how to parse JSON in Javascript. Just wanted to make a quick post to share so we can have a reference to look back to.

Let’s say we have a some JSON data stored a variable:

var data = '[{"name": "python", "experience": "1 year", "learn" : "true"}, 
            {"name": "javascript", "experience":"3 years", "learn" : "true"}]'; 

We can parse the JSON data using the JSON.parse() method.

 var language = JSON.parse(data);  

Now what if we want to store the data into a list? Let’s create the placeholder for it.

 <ul id="output"></ul> 

To make our lives easier we can use the $.each() jQuery function to loop through the data.

 var output = $("#output"); 
 $(document).ready(function() { 
     $.each(language, function(){ 
         $('<li>' + this.name + '</li>').appendTo(output); 
      }); 
  });

However, you can do this in vanilla Javascript as well.

var output = document.getElementById("output"); 
for (var i in language) { 
    output.innerHTML = '<li>' + langauge[i].name + '</li>'; 
}    

Here is the code(fiddle) for reference.

Tyler Souza

Tyler is a very passionate full-stack developer who thrives on a challenge. He specializes in programming (mainly in Python), REST API development, and keeps up with the latest front-end technologies. When not coding, he loves to eat ramen, BBQ, and travel.

You may also like...