DEV Community

Alisa Bajramovic
Alisa Bajramovic

Posted on

What is JSON and why is it useful?

JavaScript Object Notation, also known as JSON, is a method used to store and exchange data. While it's commonly used with JavaScript, it can be used with other languages as well, including C, C++, C#, and Python, and therefore is considered language independent. Programmer Douglas Crockford is credited with expanding and popularizing JSON in the early 2000s, but it was not until 2013 that it became officially standardized.

Browsers and servers can only communicate using text, such as JSON. JavaScript can easily be converted to JSON, and vice-versa, thus enabling the communication of JS objects. JSON data is written as key-value pairs. The key must be a string, and the value can be an object, array, boolean, string, number, or a null value. JSON values cannot be undefined, a date, or a function.

In order to send a JS object from the browser to a server, you can convert the object to JSON using JSON.stringify(). Using this function turns JS into a string, which is readable by the server. For example:

let objectExample = {
  firstName: "Sam",
  favoriteColor: "blue"
};
let jsonExample = JSON.stringify(objectExample);

Enter fullscreen mode Exit fullscreen mode

In order to receive JSON from the server to readable JS, you can convert it back to a JavaScript object using JSON.parse(). When data is received by a browser, it comes as a string, and thus JSON.parse() is used to turn it into a JS object. For example:

let jsonExample = '{"firstName":"Sam", "favoriteColor":"blue"}';
let objectExample = JSON.parse(jsonExample);
Enter fullscreen mode Exit fullscreen mode

In both of these examples, the manipulation of JS/JSON was done on the client's side. Yet, if there is a need to use the data in any way on the server itself, then server-side manipulation will also be necessary.

JSON objects, which are written using curly brackets, can be accessed and manipulated in similar ways to JavaScript objects. JSON object values can be accessed using both dot and bracket notation. For example:

jsonExample = '{"firstName":"Sam", "favoriteColor":"blue"}';
x = jsonExample.firstName
y = jsonExample["favoriteColor"]
Enter fullscreen mode Exit fullscreen mode

You also can modify or delete the values in these objects using both dot and bracket notation. In order to delete a property, use the delete keyword:

jsonExample = '{"firstName":"Sam", "favoriteColor":"blue"}';
delete jsonExample.favoriteColor

Enter fullscreen mode Exit fullscreen mode

JSON is an extremely valuable and straightforward tool for every JavaScript developer. It is a key feature in asynchronous code, which enables pages to load faster.


For more information:

Top comments (0)