Introduction to JSON, JSON Examples and How JSON differs from XML

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.  JSON is a text format that is completely language independent.  It originates from the JavaScript language, Standard ECMA-262 3rd Edition – December 1999 and is represented with two primary data structures: ordered lists (recognized as ‘arrays’) and name/value pairs (recognized as ‘objects’).

Why You will use JSON?

The JSON standard is language-independent and its data structures, arrays and objects, are universally recognized. These structures are supported in some way by nearly all modern programming languages and are familiar to nearly all programmers. These qualities make it an ideal format for data interchange on the web.

How JSON differs from XML?

The XML specification does not match the data model for most programming languages which makes it slow and tedious for programmers to parse. Compared to JSON, XML has a low data-to-markup ratio which results in it being more difficult for humans to read and write.

JSON Examples:

Array –
myArray = [ “John Doe”, 30, false, null ]

You can assign value of an array element like below in javascript –
myArray[1] = 50

Object –
myObject = {
“first”: “John”,
“last”: “Doe”,
“age”: 30,
“sex”: “M”,
“salary”: 50000,
“subcription”: false
}

You can assign value of an object property like below in javascript –

myObject.salary = 50000

myObject[“salary”] = 50000

Array with objects –
myArray = [
{ “name”: “John Doe”, “age”: 30 },
{ “name”: “Michel Smith”, “age”: 34 },
{ “name”: “Jonas Scott”, “age”: 49 }
]

You can assign value of an object property like below in javascript –

myArray[0].name = John Doe

Object with nested arrays and objects –
myObject = {
“first”: “John”,
“last”: “Doe”,
“age”: 35,
“sex”: “M”,
“salary”: 50000,
“registered”: true,
“interests”: [ “Reading”, “Blogging”, “Hacking” ],
“favorites”: {
“color”: “Green”,
“sport”: “Cricket”,
“food”: “Fish Fry”
},
“skills”: [
{
“category”: “JavaScript”,
“tests”: [
{ “name”: “One”, “score”: 60 },
{ “name”: “Two”, “score”: 76 }
]
},
{
“category”: “Spring”,
“tests”: [
{ “name”: “One”, “score”: 59 },
{ “name”: “Two”, “score”: 74 }
]
}
]
}

You can assign value of a property like below in javascript –

myObject.skills[0].category = Java

myObject[“skills”][0][“category”] = Java

myObject.skills[1].tests[0].score = 80

myObject[“skills”][1][“tests”][0][“score”] = 80

Gopal Das
Follow me

Leave a Reply

Your email address will not be published. Required fields are marked *