Last updated on May 5th, 2016 at 01:00 am
According to WIKI JavaScript Object Notation, is an open standard format that uses human-readable text to transmit data objects consisting of attribute–value pairs. It is used primarily to transmit data between a server and web application, as an alternative to XML.
W3schools says that
For AJAX applications, JSON is faster and easier than XML:
If we get an xmp from a ajax response then we need to
1)Fetch an XML document
2)Use the XML DOM to loop through the document
3)Extract values and store in variables
If we use JSON instead then all you have to do is Fetch a JSON string and eval() the JSON string
Below is the entire code for parsing simple JSON object and read each value using javascript. Hope this will be helpful for someone 🙂
var anyobj = { "Title": "The Cuckoo's Calling", "Author": "Robert Galbraith", "Genre": "classic crime novel", "Detail": { "Publisher": "Little Brown", "Publication_Year": 2013, "ISBN-13": 9781408704004, "Language": "English", "Pages": 494 }, "Price": [ { "type": "Hardcover", "price": 16.65 }, { "type": "Kidle Edition", "price": 7.03 } ], "Students": [ { "Name":"Jack" , "Major":"Physics" }, { "Name":"Sam" , "Major":"Chemistry" }, { "Name":"Michael" , "Major":"Mathematics" } ] };
The anyobj is our JSON object so all we are going to do is parse this object just like we parse an xml file.
Refer the links below for how to parse XML
Simple XML Parsing Using PHP
XML Parsing Made Easy
The entire code will look like this
<!DOCTYPE html> <html> <body> <h2>JSON Object Creation in JavaScript</h2> <p> Title: <span id="jtitle"></span><br> Publisher: <span id="jpublish"></span><br> Price: <span id="jprice"></span><br> Student Details <span id="jstud"></span><br> </p> <script> var anyobj = { "Title": "The Cuckoo's Calling", "Author": "Robert Galbraith", "Genre": "classic crime novel", "Detail": { "Publisher": "Little Brown", "Publication_Year": 2013, "ISBN-13": 9781408704004, "Language": "English", "Pages": 494 }, "Price": [ { "type": "Hardcover", "price": 16.65 }, { "type": "Kidle Edition", "price": 7.03 } ], "Students": [ { "Name":"Jack" , "Major":"Physics" }, { "Name":"Sam" , "Major":"Chemistry" }, { "Name":"Michael" , "Major":"Mathematics" } ] }; document.getElementById("jtitle").innerHTML=anyobj.Title document.getElementById("jpublish").innerHTML=anyobj.Detail.Publisher document.getElementById("jprice").innerHTML=anyobj.Price[1].type document.getElementById("jstud").innerHTML=anyobj.Students[1].Name </script> </body> </html>
The output of the above script will be
JSON Object Creation in JavaScript Title: The Cuckoo's Calling Publisher: Little Brown Price: Kidle Edition Student Details Sam