What is JSON?

JavaScript Object Notation, or JSON, is way to store and transfer information. JSON is a way of storing JavaScript objects as strings. When transferring data between servers and clients the data must be sent in text. This means we cannot send JavaScript objects as they are, they must be transferred into text which is where JSON comes in.

Below is an example of a simple JavaScript object. The object is stored within a variable called ‘person’ that has four fields, which comprises of two strings one number and one boolean value type. The string values are the only ones that are encased within double quotes.

var person = {
    firstName: "John",
    lastName: "Doe",
    age: 31,
    member: true

The same object from above is shown below but in JSON format, this could be stored within a file that ends with a ‘.json’ file type suffix. As you can see when using JSON format the variable names are now encased within double quotes. Within JSON documents the only things not put within double quotes are number values and boolean values.

    "firstName": "John",
    "lastName": "Doe",
    "age": 31,
    "member": true

You can convert JavaScript objects to JSON within JavaScript code. Using the ‘JSON’ object and the ‘stringify’ method you can pass the JavaScript object and it will return the object converted into a JSON format. This can be useful when sending data from the client to the server, as it will need to be in JSON format or a text format.

var myJson = JSON.stringify(myObj);

When receiving JSON data from a server you can ‘parse’ the JSON into a normal JavaScript object using the ‘parse’ method of the ‘JSON’ object. This means you can convert a JSON string send from the server into a normal JavaScript object.

var myObj = JSON.parse(myJson);

JSON can be used to send and receive data from a server, and using JavaScript you can convert in between JSON and normal JavaScript objects. This means you could create a object in JavaScript, send it to a server in JSON format, and modify the object by converting between JavaScript and JSON.

Leave a Reply