What is JSON Format and How to Create your own JSON ?

JSON - JavaScript Object Notation format is most widely used in web applications. If you have worked with different API's then you may find most of them give the response in JSON format.

What is JSON ?

It's a simple format of javascript objects. It has some syntax such as key-value pairs in curly brackets { } and arrays enclosed in square brackets [ ]. Keys in JSON can have the value as a string, number, array or boolean values etc.

In simple, JSON is a lightweight structure to send data on web that is understandable by all browsers. Didn't get the point yet? Have a look at the example below.

{
"employees":[
    {"firstName":"John""lastName":"Doe"},
    {"firstName":"Anna""lastName":"Smith"},
    {"firstName":"Peter""lastName":"Jones"}
]
}

Why JSON ?

Here are some reasons why JSON is said to be the best data format.

- Easy understanding, self-describing, clean and well structured.
- Light on the network.
- Much easier to parse compared to XML  or any other format.

Can I write my own data in JSON ?

Yes, But before you start you need to learn some rules that you have to follow while writing JSON data.

As I said before, Key values are written in curly brackets and arrays are enclosed in square brackets.

In JSON name/value pairs consists of a name (in double quotes), followed by a colon, followed by the value of the key

"firstName":"aravind"
To write the JSON object that can contain multiple name/value pairs :


{"firstName":"aravind""lastName":"chowdary"}
Coming to arrays in JSON that are written in square brackets :

"employees":[
    {"firstName":"aravind""lastName":"chowdary"},
    {"firstName":"John""lastName":"Smith"},
    {"firstName":"Peter""lastName":"Jones"}
]

Convert JSON to Javascript Object

Mostly JSON is used to read data on a web application or display data on the web. For that, we'll need to convert JSON into Javascript objects.

For easy understanding lets look at an example :

var text = '{ "employees" : [' +
'{ "firstName":"aravind" , "lastName":"chowdary" },' +
'{ "firstName":"John" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';


To parse above text use buit in the function ( JSON.parse() ) in javascript.

var obj = JSON.parse(text);

That's all about JSON. Hope you learnt something new.

Happy Koding !