JSON ( Java Script Object Notation) is a lightweight data-interchange format compared to XML.
JSON format is easy to read and write for developers and supports text format.
- A JSON object starts with { (left brace) and ends with (Left braces ) }
- .name/value is defined by : (colon)
Like { “Name”:” Neeraj”}
- .name/value pairs separated by , (comma)
{“first”:” Neeraj”,” second”:” Kumar”}
- JSON data Structure:
Object:
{“key1”:”value1”,”key2”:”value2”}
Ex:
{“first”:” Neeraj”,” second”:” Kumar”}
Array:
[“first”,” second”,” third”]
Number:
12 23
String:
“this is a text”
Boolean:
True False
- Personal information about a Person in JOSN:
- {
- “name”:” Neeraj Kumar”,
- “birthday”:” November 5 1994”,
- “address”: “Behind atta Mandir, Alwar,Rajasthan, INDIA”
- }
Another way of representing the same information in JSON:
- {“first_name”: ”Neeraj”,
- “last_name”: ”Kumar”,
- “birthday”: ”11 - 5 - 1994”“address”: {“street”: ”Behind Atta Mandir”,
- “City”: ”Alwar”,
- “State”: ”Rajasthan”,
- “Country”: ”INDIA”
- }
- }
Both are the same but the second example clears all information about the person and it is a formal way of representing the data of a person.
- JSON Schema according to Second Example:
- {
- "type": "object",
- "properties": {
- "first_name": {
- "type": "string"
- },
- "last_name": {
- "type": "string"
- },
- "birthday": {
- "type": "string",
- "format": "date-time"
- },
- "address": {
- "type": "object",
- "properties": {
- "street": {
- "type": "string"
- },
- "city": {
- "type": "string"
- },
- "State": {
- "type": "string"
- },
- "Country": {
- "type": "string"
- }
- }
- }
- }
- }
- JSON Object in javascript:
- Var jsObject=JSON.parse(data);
Ex:
- <html>
- <title>JSON object in javascript</title>
- <body>
- <h2 id="jsonobject"></h2>
- <script>
- var myProfile = '{"first_name":"Neeraj Kumar","last_name":"Kumar","address":{"street":"Behind atta mandir","city":"Alwar","State":"Rajasthan","Country":"INDIA"}}';
- var jsObject = JSON.parse(myProfile);
- document.getElementById("jsonobject ").innerHTML =
- jsObject.first_name + "
- <br>" +
- jsObject.last_name + "
- <br>" +
- jsObject.address.street + "
- <br>" +
- jsObject.address.city + "
- <br>" +
- jsObject.address.State + "
- <br>" +
- jsObject.address.Country ;
-
- </script>
- </body>
- </html>
Member can be access using . (dot).