Modern JavaScript: JSON Stringify and Parse
Welcome to the JSON Stringify and Parse lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
In the past, we had to use third-party libraries to read and write JSON. Fortunately, modern versions of JavaScript include built-in JSON support.
>
JSON.stringify({a: 2}) === '{"a":2}';Result:
>
JSON.parse('{"a": 1, "b" : 2}');Result:
The
stringifymethod turns a JavaScript object or value into a JSON string. By default, it will pack the JSON tightly. For example, there's no space after the:in the stringified object above. Theparsemethod turns a JSON string back into an object.By combining the two methods, we can "round-trip" an object to JSON and back, ending up with the same object that we started with.
>
JSON.parse(JSON.stringify({name: 'Amir'}));Result:
{name: 'Amir'}If we try to parse a string that isn't valid JSON, we'll get an error. (You can type
errorwhen a code example will throw an error.)>
JSON.parse('*@& oh no &@*')Result:
SyntaxError: Unexpected token '*', "*@& oh no &@*" is not valid JSON
JSON stands for "JavaScript object notation". However, not all JavaScript object syntax is valid JSON.
The full details of JSON's syntax are out of scope for this course, but we'll review one quick example to make the point. JavaScript object keys don't require quotes, but JSON keys do. If we try to parse a JSON string with unquoted object keys, we'll get an error.
>
JSON.parse('{"a": 1}');Result:
{a: 1}>
JSON.parse('{a: 1}')Result:
SyntaxError: Expected property name or '}' in JSON at position 1
The JSON methods will parse and stringify any JSON-compatible value, not just objects. They work on arrays, strings, numbers, etc.
>
JSON.parse(JSON.stringify([1, 2]));Result:
[1, 2]
>
JSON.parse(JSON.stringify('hello'));Result:
'hello'
>
JSON.parse(JSON.stringify([true, null]));Result:
[true, null]
undefinedis an important special case because it's not allowed in JSON. When we callstringify, anyundefineds in the original object will be turned intonulls. If we thenparsethe resulting JSON, we'll get anullout. The JSON contains no hints that there ever was anundefined.>
JSON.stringify([1, undefined, 2]);Result:
>
JSON.parse(JSON.stringify([1, undefined, 2]));Result:
[1, null, 2]
JSON can't represent circular objects (objects that reference themselves). Here's an example of a circular object.
>
const circularObject = {};circularObject.someKey = circularObject;circularObject;Result:
If we try to stringify a circular object, we get an error.
>
const circularObject = {};circularObject.someKey = circularObject;JSON.stringify(circularObject);Result:
TypeError: Converting circular structure to JSON --> starting at object with constructor 'Object' --- property 'someKey' closes the circleSometimes, we want an object to specify how it should be serialized to JSON. We can do that by putting a function in its
toJSONproperty.JSON.stringifywill automatically call that function and use its result rather than the original object.>
const user = {name: 'Amir',toJSON: () => 'This is Amir!'};JSON.parse(JSON.stringify(user));Result:
The
toJSONfunction isn't responsible for actually converting to JSON;stringifywill still do that part. Instead,toJSONreturns a new JavaScript value to be serialized in place of the original.>
JSON.parse(JSON.stringify({name: 'Amir',toJSON: () => ({thisWas: 'Amir'})}));Result:
{thisWas: 'Amir'}