The data toolbox

INPUT · Slides

Converting to and from JSON

01 / 05

Objects cannot be sent as-is

An object in memory like { name: "Yui", age: 15 } cannot simply be saved to a file or sent across a network to another computer as-is.

To pass it outside, it must be turned into a standard plain text string that anyone can read. The worldwide format for this is JSON.

02 / 05

Stringifying with JSON.stringify

Calling JSON.stringify(val) converts an object or array into a JSON-formatted string.

In JSON, both keys and string values are always enclosed in " (double quotes).

const user = { name: "Yui", age: 15 };const text = JSON.stringify(user);console.log(text);console.log(typeof text);

Result

{"name":"Yui","age":15}
string

03 / 05

Restoring with JSON.parse

When you receive a JSON string, you can turn it back into a JavaScript object with JSON.parse(str).

Once restored, you can access properties with dot notation as usual.

const text = '{"name":"Yui","age":15}';const user = JSON.parse(text);console.log(user.name);console.log(user.age);

Result

Yui
15

04 / 05

Arrays can be JSON too

Not just objects: arrays can also be converted to JSON directly.

[1, 2, 3] stringified becomes "[1,2,3]", and parsed returns the original array.

const colors = ["red", "blue"];const jsonText = JSON.stringify(colors);console.log(jsonText);const restored = JSON.parse(jsonText);console.log(restored[0]);

Result

["red","blue"]
red

05 / 05

Check the key points

Let us review the ideas:

  • JSON.stringify(data): converts objects or arrays to strings
  • JSON.parse(str): parses JSON strings back into objects or arrays
  • The industry standard for data transfer and storage

Let us try converting data!