HTML Dog
Skip to navigation

JSON

JSON — JavaScript Object Notation — is a set of text formatting rules for storing and transferring data in a machine and human readable way. It looks a lot like the object literal syntax of JavaScript, and it is from there JSON originates.

But JSON is not JavaScript. Officially it’s a totally different language with its own spec but it plays such a big part in JavaScript development that it’s important to cover.

Here’s some JSON:


{ "name": "Yoda", age: 894, "lightsaber" : { "color": "green" } }

Like in JavaScript, the brace notation is used.

JSON is used to transfer information - between your browser to a server, or saved in text files for retrieval later - because it’s simply text. That means you can’t store complex data like a function, but you can store arrays, objects containing simple data, strings and numbers.

Using JSON

Data is either converted to or from JSON, using methods called stringify and parse respectively. JSON is an object available in pretty much all modern browsers but there are ways of adding to a browser that doesn’t have it.


var jsonString = JSON.stringify({
    make: "McLaren",
    model: "MP4-12C",
    miles: 5023
});

JSON.stringify converts an object into a JSON string. In this example, jsonString becomes {"make": "McLaren", "model": "MP4-12C", "miles": 5023 }.


var car = JSON.parse(jsonString);

The string can then be converted back to a JavaScript object using JSON.parse. car is now usable as a normal JavaScript object, so you can set its properties:


car.model = "P1";