Execute Program

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 stringify method 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. The parse method 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'}Pass Icon
  • If we try to parse a string that isn't valid JSON, we'll get an error. (You can type error when a code example will throw an error.)

  • >
    JSON.parse('*@& oh no &@*')
    Result:
    SyntaxError: Unexpected token '*', "*@& oh no &@*" is not valid JSONPass Icon
  • 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}Pass Icon
  • >
    JSON.parse('{a: 1}')
    Result:
    SyntaxError: Expected property name or '}' in JSON at position 1Pass Icon
  • 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]Pass Icon
  • >
    JSON.parse(JSON.stringify('hello'));
    Result:
    'hello'Pass Icon
  • >
    JSON.parse(JSON.stringify([true, null]));
    Result:
    [true, null]Pass Icon
  • undefined is an important special case because it's not allowed in JSON. When we call stringify, any undefineds in the original object will be turned into nulls. If we then parse the resulting JSON, we'll get a null out. The JSON contains no hints that there ever was an undefined.

  • >
    JSON.stringify([1, undefined, 2]);
    Result:
  • >
    JSON.parse(JSON.stringify([1, undefined, 2]));
    Result:
    [1, null, 2]Pass Icon
  • 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 circlePass Icon
  • Sometimes, we want an object to specify how it should be serialized to JSON. We can do that by putting a function in its toJSON property. JSON.stringify will 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 toJSON function isn't responsible for actually converting to JSON; stringify will still do that part. Instead, toJSON returns a new JavaScript value to be serialized in place of the original.

  • >
    JSON.parse(
    JSON.stringify(
    {
    name: 'Amir',
    toJSON: () => ({thisWas: 'Amir'})
    }
    )
    );
    Result:
    {thisWas: 'Amir'}Pass Icon