Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 39 ยท JSON

JSON.parse and JSON.stringify

Convert JSON text to JavaScript values and back with JSON.parse and JSON.stringify. Learn pretty-printing, indentation and safe error handling.

JavaScript has a built-in JSON object with two methods that you will use constantly. JSON.parse() turns JSON text into a JavaScript value. JSON.stringify() turns a JavaScript value into JSON text. Everything that crosses the network as JSON passes through one of them: you stringify before sending, and you parse (or call response.json(), which parses for you) after receiving.

flowchart LR
    T["JSON text<br/>(a string)"] -- "JSON.parse()" --> O["JavaScript value<br/>(object, array, ...)"]
    O -- "JSON.stringify()" --> T

Parsing and stringifying are inverse operations, with a few lossy edges.

This page is a practical guide. For the full list of parameters and edge cases see the reference pages for JSON.parse() and JSON.stringify().

JSON.parse: text to value

Pass it a string that contains valid JSON and it returns the corresponding value.

JS Parsing JSON text

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A few things to remember:

  • The input must be a string. If you pass something else, JavaScript converts it to a string first. JSON.parse(undefined) and JSON.parse({}) both throw, because the strings "undefined" and "[object Object]" are not JSON.
  • The output uses only the six JSON types, plus real JavaScript numbers. Dates stay strings.
  • response.json() is JSON.parse() applied to the response body, returning a promise.

JSON.stringify: value to text

JSON.stringify(value) returns a string. By default it is compact: no spaces, no line breaks, which is best for sending over a network.

JavaScript
JSON.stringify({ name: "Ada", skills: ["math", "code"], active: true });
// '{"name":"Ada","skills":["math","code"],"active":true}'

It follows these rules:

  • Object properties are written in their own order, using only own enumerable string keys.
  • undefined, functions and symbols are skipped in objects and written as null inside arrays.
  • NaN and Infinity become null.
  • Dates become ISO strings (through their toJSON() method, see the next lesson).
  • If the top-level value itself is undefined, a function or a symbol, the result is undefined, not a string.
  • BigInt values throw a TypeError, and circular references throw a TypeError too.

Pretty-printing with the space argument

The third argument controls indentation. A number gives that many spaces (capped at 10); a string is used as the indent text itself.

JS Indentation and pretty-printing

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second argument, here null, is the replacer, which can filter or transform values. In its simplest form it is an array of property names to keep:

JavaScript
const user = { id: 1, name: "Ada", password: "secret", email: "[email protected]" };

JSON.stringify(user, ["id", "name"]);
// '{"id":1,"name":"Ada"}'

The array form is a handy allow-list, but it applies at every nesting level. The function form, and its partner for parsing, are covered in Revivers, Replacers and toJSON.

Use pretty-printing for logs, config files and debugging; send compact JSON over the network, because whitespace only adds bytes.

Sending JSON with fetch

Stringify belongs at the boundary where data leaves your code. A POST request combines JSON.stringify() with a JSON Content-Type:

JavaScript
const response = await fetch("https://api.example.com/comments", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ postId: 42, text: "Great article!" }),
});
const saved = await response.json();

Forgetting JSON.stringify is a classic mistake: passing an object as body sends the text [object Object].

Handling invalid JSON

JSON.parse() throws a SyntaxError when the text is not valid JSON. Data from outside your program, such as API responses, user input and files, can always be broken, so parse it inside try/catch.

JS A safe parsing helper

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two cautions about the fallback pattern:

  • Catching only SyntaxError means real bugs are not hidden behind a quiet default.
  • A fallback silently turns a broken payload into an empty one. For critical data, report the failure rather than pretend it is fine.

Error message wording differs between browsers and engines ("Unexpected token", "Expected property name", and so on), so never match on message text. Check the error type, and use the message only for logging.

Valid JSON is not trusted data

Parsing only proves the syntax is right. JSON.parse('{"age":"not a number"}') succeeds. A parsed object can have missing fields, wrong types or extra properties, so validate what you use. Validating JSON Data shows how.

One more use that comes up in practice is a quick deep copy: JSON.parse(JSON.stringify(value)). It works for plain data but drops everything JSON cannot hold, so prefer structuredClone() for general copying. The reviver lesson shows the pitfalls.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does JSON.stringify({ a: undefined, b: 1 }) return?

    Properties whose value is undefined are skipped in objects. Inside arrays they become null instead.
  2. 2. Which call produces a pretty-printed result indented by 4 spaces?

    The indentation is the third argument. The second argument is the replacer, so pass null when you do not need one.
  3. 3. Why should you wrap JSON.parse in try/catch for data from outside your program?

    JSON.parse is synchronous and throws on invalid input. Without try/catch, one bad payload can stop your code.
  4. 4. You pass an object directly as the body of a fetch POST request, with no JSON.stringify. What is sent?

    fetch only converts known body types such as strings, FormData and URLSearchParams. A plain object becomes the string [object Object].
  5. 5. Does a successful JSON.parse prove the data has the shape your code expects?

    Syntax and shape are different problems. Fields can be missing or have the wrong type, so validate parsed data before using it.

Summary

  • JSON.parse(text) converts JSON text to a value; JSON.stringify(value) converts a value to text.
  • response.json() is parsing the body for you, and a POST body needs JSON.stringify plus a JSON Content-Type.
  • The third argument of stringify sets indentation: a number of spaces (up to 10) or a string; the second argument is the replacer.
  • undefined, functions and symbols are skipped in objects and become null in arrays; NaN becomes null; BigInt and circular references throw.
  • JSON.parse throws a SyntaxError on invalid text, so wrap it in try/catch and check the error type instead of the message.
  • Valid syntax does not mean valid data; validate the shape before you rely on it.

Next: Revivers, Replacers and toJSON โ€” transform values while parsing and serializing.