What is JSON?

JSON means JavaScript Object Notation which is a light-weight, human-readable format for storing and exchanging data. This is an language independent format that most programming and scripting languages support. It is also the most popular data exchange format. JSON documents are very easy to read and is very lightweight and can be saved in files with .json extension. The following is an example of a JSON document as a JavaScript object.


var person1 = 
    {
        "name" : "John",
        "age" : 29,
        "address" : {
            "street address" : "123 george st",
            "city" : "Sydney",
            "state" : "NSW"
        },
        "cities_visited" : [ "Sydney", "Melbourne", "Delhi", "New York" ]
    };

The above example shows the format of a json document and some of the data types that can be used. A JSON document contains name value pairs where the value can be a string, number, array and another object and each of the properties are separated with a comma.

The media type for JSON is application/json.

Uses of JSON format

To summarise, JSON documents are usually used for the following purpose.

  • Within JavaScript based applications used within websites
  • For transmitting structured data over network
  • A popular data transfer format used by web services
  • Can be used by most programming languages

Sending and Parsing Data

Though JSON uses JavaScript object format, it is still text that can be parsed. It is very common for web services to transfer data using JSON as browsers can easily parse the data using JavaScript. JavaScript can use the parse method to parse the data as an JavaScript object. JavaScript object can also be easily converted to JSON by using the JavaScript's stringify method.


//convert object to JSON
var person1 = 
    {
        "name" : "John",
        "age" : 29,
        "address" : {
            "street address" : "123 george st",
            "city" : "Sydney",
            "state" : "NSW"
        },
        "cities_visited" : [ "Sydney", "Melbourne", "Delhi", "New York" ]
    };

var jsonStr = person1.stringify(person1);


//parse string as JSON
//note person1 object is inside `` which can be used for multiline string

var person1 = 
    `{
        "name" : "John",
        "age" : 29,
        "address" : {
            "street address" : "123 george st",
            "city" : "Sydney",
            "state" : "NSW"
        },
        "cities_visited" : [ "Sydney", "Melbourne", "Delhi", "New York" ]
    };`

var jsonObj = person1.parse(person1);