How to use JSON.stringify() and JSON.parse() in JavaScript

How to use JSON.stringify() and JSON.parse() in JavaScript

JSON.stringify() and JSON.parse() are useful tools for handling JSON-formatted content

Image for postStringify turns objects like { foo: ?bar? } into JSON strings like {?foo?: ?bar?} (Photo by davide ragusa on Unsplash)

JavaScript has two useful methods to deal with JSON-formatted content: JSON.stringify() & JSON.parse(), which are useful to learn as a pair.

  • JSON.stringify() takes a JavaScript object and then transforms it into a JSON string.
  • JSON.parse() takes a JSON string and then transforms it into a JavaScript object.

Let?s take a look at a code example:

JSON.stringify() can take additional arguments, a replacer function and a string or number to use as a ?space? in the returned string.

That means the replacer argument can be used to filter out values if you return undefined, as shown in the following example:

Can JSON.parse and JSON.stringify be used to deep copy objects?

A frequent code example in discussions of deep cloning in JavaScript is wrapping JSON.parse around JSON.stringify to make a deep copy of an array or object ? meaning deeply nested arrays or objects will be copied.

However, be careful with this method, as it will not work for many data types, including undefined, Date objects, RegExp objects, and Infinity:

If you are sure your deeply nested data only includes strings, numbers, boolean, and null, then yes you can use parse & stringify to deep copy.

But a more-reliable way to deep copy objects and arrays in JavaScript is using a custom function or a helper library, such as rfdc, as I discuss here:

How to Deep Copy Objects and Arrays in JavaScript

The usual methods of copying an object or array only make a shallow copy, so deeply-nested references are a problem?

medium.com

Image for postHow do you spell stringify backwards? JSON.parse() (Photo by clement fusil on Unsplash)

20

No Responses

Write a response