JSON is the default format for web APIs and a large share of configuration files. This guide covers its syntax, the mistakes that cause most parse errors, how to work with it in JavaScript, validation with JSON Schema, and converting it to other formats.

What Is JSON and Why Did It Win?

JSON stands for JavaScript Object Notation. Douglas Crockford popularized it in the early 2000s as a lightweight alternative to XML for data interchange. The idea was simple: take the object literal syntax that JavaScript developers already knew and use it as a universal data format.

Before JSON took off, XML was the dominant format for web services. SOAP APIs sent XML back and forth with verbose tags, namespaces, and schemas. A simple user record in XML might look like this:

<user>
  <name>Alice</name>
  <age>30</age>
  <active>true</active>
</user>

The same data in JSON is noticeably shorter and easier to read:

{
  "name": "Alice",
  "age": 30,
  "active": true
}

JSON spread because it is less verbose, maps directly to native data structures in most languages, and is easy to read. It is standardized as ECMA-404 and RFC 8259. Today it is used in REST APIs, document databases like MongoDB, package manifests like package.json, and many configuration files. To format or validate a document, use the JSON Formatter and Validator.

JSON Syntax Rules

JSON has six data types: object, array, string, number, boolean, and null.

Objects

An object is an unordered collection of key-value pairs wrapped in curly braces. Keys must be strings (in double quotes), and each key-value pair is separated by a comma:

{
  "firstName": "Bob",
  "lastName": "Smith",
  "role": "developer"
}

Arrays

An array is an ordered list of values wrapped in square brackets:

["JavaScript", "Python", "Rust", "Go"]

Strings, Numbers, Booleans, and Null

Strings must use double quotes. Numbers can be integers or floating-point, with no leading zeros, no hex, and no NaN or Infinity. Booleans are lowercase true or false, and null represents an empty value.

JSON itself puts no limit on number size, but JavaScript numbers lose precision above 253 - 1. JSON.parse("9007199254740993") returns 9007199254740992, which is why many APIs send large IDs as strings.

Nesting

These types can be nested inside each other. A more realistic example:

{
  "user": {
    "id": 42,
    "name": "Alice",
    "emails": ["[email protected]", "[email protected]"],
    "address": {
      "city": "Portland",
      "state": "OR",
      "zip": "97201"
    },
    "verified": true,
    "deletedAt": null
  }
}

Common Mistakes That Trip People Up

Most "invalid JSON" errors come from a short list of mistakes:

Trailing commas. JavaScript lets you put a comma after the last item in an array or object. JSON does not. This is probably the single most common source of parse errors:

// INVALID - trailing comma
{
  "name": "Alice",
  "age": 30,
}

Single quotes. JSON requires double quotes for strings and keys. Single quotes will cause a parse failure immediately:

// INVALID - single quotes
{'name': 'Alice'}

Comments. JSON does not support comments of any kind. No //, no /* */. If you need comments in a configuration file, consider using JSONC (JSON with Comments, supported by VS Code) or switch to YAML. You can convert between these formats using our JSON to YAML converter.

Unquoted keys. In JavaScript, you can write { name: "Alice" }. In JSON, that key must be in double quotes: { "name": "Alice" }.

Working with JSON in JavaScript

JavaScript gives you two core methods for working with JSON: JSON.parse() and JSON.stringify().

Parsing JSON

The JSON.parse() method takes a JSON string and returns a JavaScript value. Always wrap it in a try-catch block, because malformed input will throw a SyntaxError:

const raw = '{"name": "Alice", "age": 30}';

try {
  const user = JSON.parse(raw);
  console.log(user.name); // "Alice"
} catch (error) {
  console.error("Failed to parse JSON:", error.message);
}

Stringifying JavaScript Objects

The JSON.stringify() method converts a JavaScript value to a JSON string. It accepts optional arguments for filtering properties and controlling indentation:

const data = { name: "Alice", age: 30, active: true };

// Compact output
JSON.stringify(data);
// '{"name":"Alice","age":30,"active":true}'

// Pretty-printed with 2-space indent
JSON.stringify(data, null, 2);
// {
//   "name": "Alice",
//   "age": 30,
//   "active": true
// }

JSON Schema: Validating Your Data

JSON Schema is a vocabulary for describing and validating the structure of JSON documents, similar in spirit to TypeScript types but checked at runtime.

Here is a simple schema that validates a user object:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "name": { "type": "string", "minLength": 1 },
    "age": { "type": "integer", "minimum": 0 },
    "email": { "type": "string", "format": "email" }
  },
  "required": ["name", "email"]
}

JSON Schema has gone through several draft versions. Draft-07 is still widely used, and Draft 2020-12 is the latest published draft. Note that format keywords such as email are treated as annotations by default, so many validators will not enforce them unless you turn that on.

The JSON Schema Validator on this site checks data against Draft 7, so remove or adapt the $schema line above when using it.

Converting JSON to Other Formats

JSON is not the best choice for every job. These are the most common conversions.

JSON to CSV

When you need to open data in Excel or Google Sheets, CSV is the way to go. Flat JSON arrays convert cleanly, but nested objects require flattening. For example, this JSON:

[
  { "name": "Alice", "age": 30, "city": "Portland" },
  { "name": "Bob", "age": 25, "city": "Seattle" }
]

becomes this CSV:

name,age,city
Alice,30,Portland
Bob,25,Seattle

Our JSON to CSV converter handles nested objects by flattening keys with dot notation, so address.city becomes a column header.

JSON to YAML

YAML is the preferred format for DevOps configuration files: Docker Compose, Kubernetes manifests, GitHub Actions workflows, and Ansible playbooks all use YAML. The same data in YAML is more concise and supports comments:

name: Alice
age: 30
emails:
  - [email protected]
  - [email protected]

Convert between the two formats instantly with our JSON to YAML converter.

JSON to TypeScript

If you work with TypeScript, you know the value of having proper type definitions for your API responses. Instead of manually writing interfaces, you can generate them from a sample JSON response. Our JSON to TypeScript converter takes a JSON object and produces TypeScript interfaces automatically.

JSON to XML

Some older systems and SOAP APIs still require XML. The JSON to XML converter handles the translation.

Useful Techniques

Pretty-Printing with a Custom Indent

The third argument to JSON.stringify() controls indentation. You can pass a number (spaces) or even a string (like a tab character):

// Tab-indented output
JSON.stringify(data, null, "\t");

// From the command line (Node.js)
// node -e "console.log(JSON.stringify(require('./data.json'), null, 2))"

Deep Cloning Objects

The old trick of JSON.parse(JSON.stringify(obj)) creates a deep clone, but it drops undefined values and functions and turns Date objects into strings. Modern JavaScript has a better option:

// Old approach (lossy)
const clone = JSON.parse(JSON.stringify(original));

// Modern approach (preserves more types)
const clone = structuredClone(original);

Use structuredClone() when you can. It preserves Date, Map, and Set, and it throws an error if the object contains a function.

JSON Lines (NDJSON)

For large datasets or streaming, JSON Lines (also called NDJSON) puts one JSON value on each line, so you can process records one at a time without loading the whole file:

{"id": 1, "event": "click", "timestamp": 1712678400}
{"id": 2, "event": "scroll", "timestamp": 1712678401}
{"id": 3, "event": "submit", "timestamp": 1712678402}

This format is widely used in logging pipelines, data engineering, and tools like jq.

Tools Mentioned in This Guide

These run in your browser and make no network request with your data: