Javascript JSON

JSON stands for Javascript Object Notation. JSON is a text-based data format that is used to store and transfer data.

{
    "name": "Mike",
    "age": 44,
    "gender": "male"
} 

In JSON, the data are in key/value pairs separated by a comma ,.

It was derived from JavaScript. So, the JSON syntax resembles JavaScript object literal syntax. However, the JSON format can be accessed and be created by other programming languages also.


JSON Data

This json type of data consists of key/value pairs similar to JavaScript object properties. The key and values are written in double quotes separated by a colon :.

"name": "Mike" 

JSON Object

JSON objects can contain multiple key/value pairs. These object is written inside curly braces { }.

{
    "name": "Mike",
    "age": 44
} 

JSON Array

This type of JSON is enclosed within array and we can have multiple objects in it. JSON array is written inside square brackets [ ].

[{
    "name": "Mike",
    "age": 44
},
{
    "name": "John",
    "age": 43
}] 

Accessing JSON Data

We can access JSON data using DOT notation.

Input:-
 <script>  
	   const employee = {
        "name": "John",
        "age": 22,
        "hobby": {
            "reading" : true,
            "sport" : "cricket"
        },
        "language" : ["HTML","JavaScript"]
    }
    document.write("Employee name is ",employee.name + "<br/>"); 
    document.write("Employee sport hobby is ",employee.hobby.sport + "<br/>"); 
    document.write("Employee language is ",employee.language[1]);
  
</script>

Output:-


Converting JSON Text to Javascript Object

Most common use of JSON is to read data from a web server, and display the data in a web page.This can be demonstrated using a string as input.

First, create Javascript string containing JSON syntax and then use Javascript built-in function JSON.parse().

Input:-
 <script>  
	   var text = 
        '{"employees":[' +
        '{"firstName":"Mike","lastName":"Graynor" },' +
        '{"firstName":"Peter","lastName":"Smith" },' +
        '{"firstName":"Zola","lastName":"Martin" }]}';

    obj = JSON.parse(text);
    document.write(obj.employees[1].firstName + " " + obj.employees[1].lastName);
</script>

Output:-