DEV Community

Cover image for What the heck is JSON.parse() and JSON.stringify()?
Sobhan Dash
Sobhan Dash

Posted on

What the heck is JSON.parse() and JSON.stringify()?

What is the JSON.parse method?

As simple as it is, the method parses a JSON string, constructing a Javascript value or object described by the string.
An optional function called reviver performs a transformation on the resulting object before being returned.

Syntax:

JSON.parse(text)
JSON.parse(text, reviver)
Enter fullscreen mode Exit fullscreen mode

What do the parameters mean?

:- text = >
It's the string to parse as JSON.

:- reviver (Optional) = >
The reviver function prescribes how the value produced originally by parsing gets transformed before being returned.

What do we get as return value?

We get a JavaScript object representing the given JSON value

Example

//1-
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]

//2- With reviver function
JSON.parse('{"p": 5}', (key, value) =>
  typeof value === 'number'
    ? value * 2 // return value * 2 for numbers
    : value     // return everything else unchanged
);

// { p: 10 }
Enter fullscreen mode Exit fullscreen mode

What is the JSON.stringify method?

The method converts a JavaScript object or value to a JSON string.
If I provide a replacer function in the optional parameters, then it will replace the specified options or include the properties.

Syntax:

JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)
Enter fullscreen mode Exit fullscreen mode

What do the parameters mean?

:- value = >
It's the value to convert to a JSON string.

:- replacer (Optional) = >
The replacer parameter can be either a function or an array.

As a function, it takes two parameters: the "key" and the "value" to be stringified. The object in which the key was found is provided as the replacer's "this" parameter.

If replacer is an array, the array's values indicate the names of the properties in the object that should be included in the resulting JSON string.

:-space (Optional) = >
The space argument may be used to control spacing in the final string.
Its mostly used for readability purposes.

What do we get as return value?

We get a JSON string representing the given value or undefined.

Example

//1- 
JSON.stringify([1, 'false', false]);   // '[1,"false",false]'

//2- With replacer function
JSON.stringify(foo, ['week', 'month']);
// '{"week":45,"month":7}', only keep "week" and "month" properties
Enter fullscreen mode Exit fullscreen mode

That's it! Now you know how to use both function.
If it was worth reading do drop a follow on my Twitter handle!

Top comments (0)