For some of you this question might be the easiest to answer. But for many developers concept of JSON is not well understood. In my seminars when I use JSON data for demo, I find many developers do not have understanding of JSON. In this post I am trying to address this problem.
In simple words, “JSON is a data interchange format. Due to its lightweight characteristics it is being highly used to exchange data between different platforms and applications”
A simple JSON data representing Students can be like following,
You can see that JSON object follows key-value pair mechanism
- Key should be always a string
- Value may be a string , number , Boolean or an object
You can represent collection in JSON as well. That can be represented as array of JSON objects.
Information about many Students can be displayed in JSON format as following,
You can have JSON object as value of another JSON object as well.
Now let us see that how can we work with JSON in JavaScript. Let us say we have a HTML page as given in the following snippet,
<body> <h2>Reading Student information from JSON data</h2> Name : <span id="namespan"></span> <br /> Marks : <span id ="marksspan"></span><br /> Addreess : <span id="addresssapn"></span> <br /> </body>
In JavaScript we have JSON data and we need to bind values of JSON in to the HTML elements. We can do that very simply as given in following snippet,
<head> <title></title> <script src="Scripts/jquery-1.7.1.js"></script> <script type="text/javascript" > $(document).ready(function () { var Student = { "name": "dj", "marks": 89, "address": { "city": "Pune", "country": "India" } }; document.getElementById('namespan').innerHTML = Student.name; document.getElementById('marksspan').innerHTML = Student.marks; document.getElementById("addresssapn").innerHTML = Student.address.city; }); </script> </head>
When you browse HTML you will find HTML elements values are displaying JSON data.
I hope now you have some understanding of JSON. Thanks for reading this post.
Leave a Reply