Mikke.Learns

How does JSON.parse and JSON.stringify work?

February 3rd, 2019

The way I understand it, JSON.stringify and JSON.parse are two Javascript methods created to work with JSON-formatted content. They are available in all modern browsers and often used when working with APIs.

JSON.stringify converts a javascript object or value to a JSON string. JSON.parse converts a JSON string into a javascript object.

Here’s an example on the stringify method:

const newPerson = { "firstName" : "Albus", "lastName" : "Dumbledore", "age" : 115, "title" : "professor", "married" : false } const newPersonString = JSON.stringify(newPerson); console.log(newPersonString); // "{"firstName":"Albus","lastName":"Dumbledore","age":115,"title":"professor","married":false}"

And here we are using JSON.parse to convert the JSON-string back to a javascript object: const newPersonString = "{"firstName":"Albus","lastName":"Dumbledore","age":115,"title":"professor","married":false}" const newPersonObject = JSON.parse(newPersonString); console.log(newPersonObject); // Object { firstName: "Albus", lastName: "Dumbledore", age: 115, title: "professor", married: false } Both methodes also works fine with arrays:

const newArray = ["pointy hat", "robe", "beard", "glasses", "wand"]; const newArrayString = JSON.stringify(newArray); console.log(newArrayString); // "["pointy hat","robe","beard","glasses","wand"]" console.log(JSON.parse(newArrayString)); // Array(5) [ "pointy hat", "robe", "beard", "glasses", "wand" ]

JSON.stringify

This method has additional functions that let us replace values with a replacer function or to only include specified properties with a replacer array and a space argument. This allows us to alter the behavior of the stringification process.

Replacer function

The replacer function takes two parameters; “key” and “value”. The object with the “key” functions as the replacer’s “this” parameter. This is so cool!

In the following example, we remove all string types.

function replace (key, value) { // Remove strings if (typeof value === 'string') { // If we return undefined, the property is not included return undefined; } return value; } const newPersonString = JSON.stringify(newPerson, replace); console.log(newPersonString); // "{"age":115,"married":false}" We can also modify the values. Here we double all numbers and remove booleans and strings: const newPersonString = JSON.stringify(newPerson, replace); function replace (key, value) { // Double the number if (typeof value === 'number') { return value * 2; } else if (typeof value === 'boolean' || typeof value === 'string') { return undefined; } return value; } console.log(newPersonString); // "{"age":230}" And here we set false booleans to true: function replace (key, value) { if (value === false) { return true; } return value; } console.log(newPersonString); // "{"firstName":"Albus" ... "married":true}"

Replacer array (whitelist)

If we instead provide an array of strings and numbers, we create a whitelist for selecting/filtering the properties of the value object to be included:

const newPersonString = JSON.stringify(newPerson, ["firstName", "age"]); console.log(newPersonString); // "{"firstName":"Albus","age":115}" Spacer The space argument is used to add space element to the JSON-string. If it’s a number it will indent the line up to 10 spaces. If it’s a string, the lines will be indented by that string (up to the first ten characters).

Space with a string:

const newPersonString = JSON.stringify(newPerson, null, ' '); console.log(newPersonString); /* "{ "firstName": "Albus", "lastName": "Dumbledore", "age": 115, "title": "professor", "married": false }" */ const newPersonString2 = JSON.stringify(newPerson, null, '...'); console.log(newPersonString); /* "{ ..."firstName": "Albus", ..."lastName": "Dumbledore", ..."age": 115, ..."title": "professor", ..."married": false }" */ Space with a number (indents by 10 spaces): const newPersonString = JSON.stringify(newPerson, null, 10); console.log(newPersonString); /* "{ "firstName": "Albus", "lastName": "Dumbledore", "age": 115, "title": "professor", "married": false }" */ JSON.parse

In addition to constructing a javascript object from a JSON string, the JSON.parse method can take a second reviver argument.

This argument is used for transforming the object values before they are returned.

const newPersonString = JSON.stringify(newPerson); function revive (key, value) { if (typeof value === 'string') { return value.toUpperCase(); } return value; } console.log(JSON.parse(newPersonString, revive)); // Object { firstName: "ALBUS", lastName: "DUMBLEDORE", age: 115, title: "PROFESSOR", married: false } One thing to note is that JSON.parse does not allow trailing commas. If present, it will throw an error.

This has been so much fun to learn. I can’t wait to try it out on APIs.