env.dev

JSON Cheat Sheet — Syntax, Parsing & Common Mistakes

Quick reference for JSON syntax: data types, objects, arrays, JSON.parse/stringify, jq basics, and common mistakes like trailing commas and single quotes.

Last updated:

JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format. It is language-independent, human-readable, and the de facto standard for APIs, configuration files, and data storage. This cheat sheet covers syntax rules, data types, parsing, serialization, command-line processing with jq, JSON Schema, common mistakes, and format variants.

JSON Data Types

JSON supports exactly six data types. Every valid JSON document is one of these at the top level.

TypeExampleNotes
string"hello world"Must use double quotes. Supports Unicode escapes.
number42, 3.14, -1, 2.5e10No hex, octal, or Infinity/NaN. No leading zeros.
booleantrue, falseLowercase only. Not 0/1.
nullnullRepresents absence of a value. Lowercase only.
object{"key": "value"}Unordered set of key-value pairs. Keys must be strings.
array[1, "two", null]Ordered list of values. Elements can be mixed types.

Syntax Rules

JSON has strict syntax rules. Violating any of these produces invalid JSON.

RuleDetail
Double quotes onlyStrings and keys must use " not ' — single quotes are invalid
No trailing commasThe last element in an array or object must not have a comma after it
No commentsJSON has no comment syntax — no //, /*, or #
Keys must be stringsObject keys must be double-quoted strings, not bare identifiers
No undefinedUse null instead — undefined is not a JSON value
UTF-8 encodingJSON text must be encoded in UTF-8 (default), UTF-16, or UTF-32
Top-level valueA valid JSON document is any JSON value (object, array, string, number, boolean, null)

Objects

An object is an unordered collection of key-value pairs enclosed in curly braces.

json
{
  "name": "Alice",
  "age": 30,
  "active": true,
  "email": null
}

Keys must be unique strings. Values can be any JSON type. Duplicate keys are technically allowed by the spec but behavior is implementation-defined — avoid them.

Arrays

An array is an ordered list of values enclosed in square brackets.

json
["apple", "banana", "cherry"]

[1, "mixed", true, null, {"nested": "object"}]

[]

Nested Structures

Objects and arrays nest freely. There is no depth limit in the spec, though parsers may impose one.

json
{
  "user": {
    "name": "Alice",
    "address": {
      "street": "123 Main St",
      "city": "Springfield",
      "coordinates": [39.7817, -89.6501]
    },
    "tags": ["admin", "verified"],
    "scores": [
      {"subject": "math", "grade": 95},
      {"subject": "science", "grade": 88}
    ]
  }
}

Strings and Escape Sequences

JSON strings support a limited set of escape sequences.

EscapeCharacter
\"Double quote
\\Backslash
\/Forward slash (optional)
\bBackspace
\fForm feed
\nNewline
\rCarriage return
\tTab
\uXXXXUnicode code point (e.g. \u00e9 for e with accent)

For characters outside the Basic Multilingual Plane (U+10000 and above), use a UTF-16 surrogate pair: \\uD83D\\uDE00 for U+1F600.

Special Values and Edge Cases

TopicDetail
Number precisionJSON numbers are arbitrary precision in the spec, but most parsers use IEEE 754 double-precision (53-bit integers max). Integers above 2^53 - 1 (9007199254740991) lose precision.
No Infinity/NaNThese are not valid JSON values. Use null or a string representation if needed.
No hexadecimalNumbers must be decimal. 0xFF is invalid JSON.
No leading zeros01 is invalid. Use 1 or 0.1.
Empty object/array{} and [] are both valid JSON documents.
Unicode in keysObject keys can contain any Unicode character: {"\u00e9": "accent e"} is valid.
WhitespaceInsignificant whitespace (spaces, tabs, newlines) is allowed between tokens.

JSON.parse() and JSON.stringify() in JavaScript

JavaScript provides two built-in methods for working with JSON.

Parsing JSON strings into objects

javascript
const data = JSON.parse('{"name": "Alice", "age": 30}');
console.log(data.name); // "Alice"

// With a reviver function to transform values during parsing
const parsed = JSON.parse('{"date": "2026-04-12"}', (key, value) => {
  if (key === 'date') return new Date(value);
  return value;
});

Converting objects to JSON strings

javascript
const obj = { name: 'Alice', age: 30, active: true };

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

// Pretty-print with 2-space indentation
JSON.stringify(obj, null, 2);

// Filter keys with a replacer array
JSON.stringify(obj, ['name', 'age']);
// '{"name":"Alice","age":30}'

// Transform values with a replacer function
JSON.stringify(obj, (key, value) => {
  if (typeof value === 'string') return value.toUpperCase();
  return value;
});
// '{"name":"ALICE","age":30,"active":true}'

Values that JSON.stringify() drops or converts

InputResult
undefinedOmitted from objects, becomes null in arrays
FunctionOmitted from objects, becomes null in arrays
SymbolOmitted from objects, becomes null in arrays
Infinity, NaNConverted to null
BigIntThrows TypeError
DateConverted to ISO string via .toJSON()
Map, SetSerialized as empty object {} (use a replacer or convert first)

Safe parsing pattern

javascript
function safeJsonParse(text) {
  try {
    return { data: JSON.parse(text), err: null };
  } catch (err) {
    return { data: null, err };
  }
}

const { data, err } = safeJsonParse(userInput);
if (err) console.error('Invalid JSON:', err.message);

jq Basics for Command-Line JSON

jq is a lightweight command-line JSON processor. See the full jq cheat sheet for comprehensive coverage.

CommandDescription
jq .Pretty-print JSON
jq .nameExtract a field
jq .users[0]First element of an array field
jq ".users[] | .name"Extract a field from every array element
jq -r .nameRaw output (no quotes around strings)
jq -c .Compact single-line output
jq "select(.age > 30)"Filter by condition
jq "keys"List object keys
jq "length"Count elements in array or keys in object
bash
# Pretty-print a file
jq . data.json

# Extract nested fields from an API response
curl -s https://api.example.com/users | jq '.data[] | {name, email}'

# Filter and count
jq '[.[] | select(.status == "active")] | length' users.json

JSON Schema Overview

JSON Schema is a vocabulary for validating the structure of JSON documents. It describes the expected shape, types, and constraints.

json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["name", "age"],
  "properties": {
    "name": {
      "type": "string",
      "minLength": 1
    },
    "age": {
      "type": "integer",
      "minimum": 0
    },
    "email": {
      "type": "string",
      "format": "email"
    },
    "tags": {
      "type": "array",
      "items": { "type": "string" },
      "uniqueItems": true
    }
  },
  "additionalProperties": false
}
KeywordPurpose
typeExpected data type (string, number, integer, boolean, object, array, null)
requiredArray of required property names
propertiesDefine schema for each property
itemsSchema for array elements
enumAllowed values: ["red", "green", "blue"]
minimum / maximumNumeric range constraints
minLength / maxLengthString length constraints
patternRegex pattern for strings
additionalPropertiesAllow or deny extra keys (true/false or a schema)
oneOf / anyOf / allOfCompose schemas with boolean logic
$refReference another schema by URI

Common Mistakes

Trailing commas

json
// INVALID - trailing comma after last element
{
  "name": "Alice",
  "age": 30,
}

// VALID
{
  "name": "Alice",
  "age": 30
}

Single quotes instead of double quotes

json
// INVALID
{'name': 'Alice'}

// VALID
{"name": "Alice"}

Comments

json
// INVALID - no comments allowed in JSON
{
  // this is a comment
  "name": "Alice"  /* inline comment */
}

// VALID - no comments
{
  "name": "Alice"
}

Unquoted keys

json
// INVALID
{name: "Alice", age: 30}

// VALID
{"name": "Alice", "age": 30}

Number precision issues

javascript
// JavaScript loses precision with large integers
JSON.parse('{"id": 9007199254740993}');
// { id: 9007199254740992 } -- precision lost!

// Solution: use strings for large IDs
// {"id": "9007199254740993"}

// Or use BigInt-aware parsing (Node.js example)
// JSON.parse(text, (key, value, { source }) => {
//   if (typeof value === 'number' && source.length > 15) return BigInt(source);
//   return value;
// });

JSON vs JSONC vs JSON5

Several extensions to JSON exist for configuration files where strict JSON is too limiting.

FormatCommentsTrailing CommasUnquoted KeysSingle QuotesUse Case
JSONNoNoNoNoData interchange, APIs, storage
JSONCYes (// and /**/)YesNoNoVS Code settings, tsconfig.json
JSON5Yes (// and /**/)YesYesYesConfig files, human-edited data

JSONC (JSON with Comments) is used by VS Code, TypeScript (tsconfig.json), and other tools. It allows // and /* */ comments plus trailing commas, but is otherwise identical to JSON.

JSON5 further relaxes syntax: unquoted keys, single-quoted strings, hex numbers, multi-line strings, Infinity, NaN, and more. It is a superset of JSON designed for hand-edited config files.

Related Tools

Use the JSON Formatter to validate and pretty-print JSON, or the JSON to TypeScript converter to generate TypeScript interfaces from JSON data.

Frequently Asked Questions

What is valid JSON?

A valid JSON document is any JSON value: an object, array, string, number, boolean (true/false), or null. The text must be encoded in UTF-8 and follow strict syntax rules: double-quoted strings, no trailing commas, and no comments.

What is the maximum size of a JSON document?

The JSON specification defines no size limit. Practical limits depend on the parser and available memory. Most HTTP APIs limit request bodies to a few megabytes. For very large datasets, consider JSON Lines (newline-delimited JSON) for streaming.

Can JSON keys be duplicated?

The RFC 8259 specification says keys SHOULD be unique but does not forbid duplicates. Behavior with duplicate keys is implementation-defined. Most parsers use the last value. Always use unique keys to avoid surprises.

Why does JSON not support comments?

Douglas Crockford deliberately excluded comments from JSON to keep it a pure data format and prevent misuse of comments as parsing directives. For configuration files that need comments, use JSONC or JSON5.

How do I handle dates in JSON?

JSON has no date type. The most common convention is ISO 8601 strings: "2026-04-12T10:30:00Z". Parse them into Date objects on the receiving end. Some APIs use Unix timestamps (integer seconds since epoch) instead.

What is JSON Lines (JSONL)?

JSON Lines is a format where each line is a valid JSON value, separated by newlines. It is useful for streaming, log files, and large datasets because you can process one line at a time without loading the entire file into memory.

Frequently Asked Questions

Can JSON have comments?

No. Standard JSON (RFC 8259) does not support comments. If you need comments, use JSONC (JSON with Comments, supported by VS Code) or JSON5. Alternatively, use a "_comment" key as a workaround.

Why does JSON require double quotes?

JSON mandates double quotes for both keys and string values. This is a deliberate design choice for simplicity and unambiguous parsing. Single quotes, unquoted keys, and trailing commas are all syntax errors in standard JSON.