Introduction to JSON Format in JavaScript

Sometimes you need to convert some data structure, such as an array or an object, to a string. This may be needed, for example, to transmit this structure across a network or save it to some kind of storage.

For this aim, a special JSON format was invented in JavaScript.

The JSON format can contain one of two structures: either an array or an object with key-value pairs. Arrays and objects are constructed in the same way as in JavaScript, but with the restriction that all strings and object string keys must be enclosed in double quotes.

Let's, for example, make a string containing an array in JSON format:

let json = '[1, 2, 3, 4, 5, "a", "b"]';

And now let's make a string containing a JSON formatted object:

let json = `{ "a": "aaa", "b": "bbb", "c": "ccc", "111": "ddd" }`;

You can arrange these structures in any order:

let json = `[ { "a": "aaa", "b": "bbb" }, { "c": "ccc", "d": "ddd" } ]`;

Unlike JavaScript structures, JSON doesn't allow commas after the last element of arrays and objects:

let json = '[1, 2, 3, 4, 5,]'; // wrong let json = '[1, 2, 3, 4, 5]'; // good

In addition to numbers and strings, the values true, false and null can also act as elements:

let json = '[null, true, false]';

Given an array:

let arr = [1, 2, 3, 'a', 'b', 'c'];

Manually convert this array to a JSON string.

Given an object:

let obj = { a: 1, b: 2, c: 'eee', d: true, };

Manually convert this object to a JSON string.

Given an object:

let obj = { a: ['a', 'b', 'c',], b: '111', c: 'eee', };

Manually convert this object to a JSON string.

enru