How To Use JSON.parse() and JSON.stringify()

How To Use JSON.parse() and JSON.stringify()

ยท

1 min read

The JSON object, available in all modern browsers, has two useful methods to deal with JSON-formatted content: ๐ฉ๐š๐ซ๐ฌ๐ž ๐š๐ง๐ ๐ฌ๐ญ๐ซ๐ข๐ง๐ ๐ข๐Ÿ๐ฒ.

๐Ÿ”น ๐‰๐’๐Ž๐.๐ฉ๐š๐ซ๐ฌ๐ž() takes a JSON string and transforms it into a JavaScript object.

๐Ÿ”น ๐‰๐’๐Ž๐.๐ฌ๐ญ๐ซ๐ข๐ง๐ ๐ข๐Ÿ๐ฒ() takes a JavaScript object and transforms it into a JSON string.

โž– ๐‘จ๐’…๐’…๐’Š๐’•๐’Š๐’๐’๐’‚๐’ ๐’‘๐’‚๐’“๐’‚๐’Ž๐’†๐’•๐’†๐’“๐’” โž–

โœ๏ธ ๐‰๐’๐Ž๐.๐ฉ๐š๐ซ๐ฌ๐ž()

It can take a ๐Ÿ๐ฎ๐ง๐œ๐ญ๐ข๐จ๐ง ๐š๐ฌ ๐š ๐ฌ๐ž๐œ๐จ๐ง๐ ๐ฉ๐š๐ซ๐š๐ฆ๐ž๐ญ๐ž๐ซ
that can transform the object values before they are returned.

In the example below the objectโ€™s values are transformed to uppercase in the returned object of the parse method.

โœ๏ธ ๐‰๐’๐Ž๐.๐ฌ๐ญ๐ซ๐ข๐ง๐ ๐ข๐Ÿ๐ฒ()

It can take ๐ญ๐ฐ๐จ ๐š๐๐๐ข๐ญ๐ข๐จ๐ง๐š๐ฅ parametes:
the first one being a ๐ซ๐ž๐ฉ๐ฅ๐š๐œ๐ž๐ซ function,
and the second ๐š ๐’๐ญ๐ซ๐ข๐ง๐  ๐จ๐ซ ๐๐ฎ๐ฆ๐›๐ž๐ซ value to use as a ๐ฌ๐ฉ๐š๐œ๐ž in the returned string.

๐“๐ก๐ž ๐ซ๐ž๐ฉ๐ฅ๐š๐œ๐ž๐ซ function can be used to filter out values, as any value returned as undefined will be out of the returned string.

๐“๐ก๐ž ๐ฌ๐ฉ๐š๐œ๐ž argument is used to insert white space into the output JSON string for readability purposes.

text

ย