← All articles

JavaScript

Working with JSON

Understand JSON values, validation and formatting.

On this page

  1. Know the syntax
  2. Parse carefully
  3. Format for readability

Know the syntax

JSON supports objects, arrays, strings, numbers, booleans and null. Object keys and strings require double quotes. Comments and trailing commas are invalid.

Parse carefully

JSON.parse throws when input is invalid. Catch exceptions and show a useful error rather than assuming input is correct.

Format for readability

JSON.stringify with a spacing argument produces indented output. Formatting is not schema validation; valid JSON can still contain unexpected fields.

Example

try {
  const value = JSON.parse(input);
  console.log(JSON.stringify(value, null, 2));
} catch (error) {
  console.error(error.message);
}

Related reading