Home 05: JSON
Content
Cancel

05: JSON

JSON is the abbrevation for JavaScript Object Notation and it can store different structures, key-value pairs (objects in JavaScript) and ordered lists of values (arrays in JavaScript).

What is it used for

The JSON format is used to store, send and receive data over the internet.

How to write JSON

How to write JSON in JavaScript

Let’s have a look at an example of how to convert an object into a JSON string.

1
2
3
let animal = { type: "cat", name: "Tom", age: 3 };
let jsonString = JSON.stringify(animal);
// '{"type":"cat","name":"Tom","age":3}'

How to read JSON in JavaScript

And here is an example of how to convert a JSON string into an object in JavaScript

1
2
3
4
5
6
7
let jsonString = '{"type": "mouse", "name": "Jerry", "age": 1}';
let animal = JSON.parse(jsonString);
// {
//     "type": "mouse",
//     "name": "Jerry",
//     "age": 1
// }

How to use it in combination with localStorage

As mentioned earlier, the WebStorage API can only store strings. What happens if we want to store a number?

1
localStorage.someNumber = 3.141592; // "3.141592"

It will be automatically converted into a string. To use it as number again, we would need to parse it back to a number.

What happens with an array?

1
localStorage.fruitArray = ["apple", "banana"]; // "apple,banana"

The content of the array will be converted into a string as well, but it is harder to turn it back into an array. One way could be to use the split method on the string and convert it into an array like in this example:

1
2
const fruitString = localStorage.fruitArray;
const fruitArray = fruitString.split(",");

But all array elements will be strings afterwards and other problems could appear.

What happens when I try to save an object into the localStorage?

1
localStorage.someObject = { answer: 42, drink: "tea" }; // "[object Object]"

We cannot convert that back to the original values.

But luckily we learned about JSON. With JSON we convert objects, arrays and other types to a string and we can store strings in the local storage.

Here is an example:

1
2
const animal = { type: "cat", name: "Tom", age: 3 };
localStorage.animal = JSON.stringify(animal);

If you want to read a value from local storage, we can use the parse method to convert it back to a JavaScript object.

1
const animal = JSON.parse(localStorage.animal);

With the help of JSON we can store numbers, arrays, and objects in local storage. This can be useful if we want to store for example a highscore list.

This post is licensed under CC BY 4.0 by the author.
Contents