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.
| Type | Example | Notes |
|---|---|---|
| string | "hello world" | Must use double quotes. Supports Unicode escapes. |
| number | 42, 3.14, -1, 2.5e10 | No hex, octal, or Infinity/NaN. No leading zeros. |
| boolean | true, false | Lowercase only. Not 0/1. |
| null | null | Represents 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.
| Rule | Detail |
|---|---|
| Double quotes only | Strings and keys must use " not ' — single quotes are invalid |
| No trailing commas | The last element in an array or object must not have a comma after it |
| No comments | JSON has no comment syntax — no //, /*, or # |
| Keys must be strings | Object keys must be double-quoted strings, not bare identifiers |
| No undefined | Use null instead — undefined is not a JSON value |
| UTF-8 encoding | JSON text must be encoded in UTF-8 (default), UTF-16, or UTF-32 |
| Top-level value | A 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.
{
"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.
["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.
{
"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.
| Escape | Character |
|---|---|
| \" | Double quote |
| \\ | Backslash |
| \/ | Forward slash (optional) |
| \b | Backspace |
| \f | Form feed |
| \n | Newline |
| \r | Carriage return |
| \t | Tab |
| \uXXXX | Unicode 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
| Topic | Detail |
|---|---|
| Number precision | JSON 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/NaN | These are not valid JSON values. Use null or a string representation if needed. |
| No hexadecimal | Numbers must be decimal. 0xFF is invalid JSON. |
| No leading zeros | 01 is invalid. Use 1 or 0.1. |
| Empty object/array | {} and [] are both valid JSON documents. |
| Unicode in keys | Object keys can contain any Unicode character: {"\u00e9": "accent e"} is valid. |
| Whitespace | Insignificant 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
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
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
| Input | Result |
|---|---|
| undefined | Omitted from objects, becomes null in arrays |
| Function | Omitted from objects, becomes null in arrays |
| Symbol | Omitted from objects, becomes null in arrays |
| Infinity, NaN | Converted to null |
| BigInt | Throws TypeError |
| Date | Converted to ISO string via .toJSON() |
| Map, Set | Serialized as empty object {} (use a replacer or convert first) |
Safe parsing pattern
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.
| Command | Description |
|---|---|
| jq . | Pretty-print JSON |
| jq .name | Extract a field |
| jq .users[0] | First element of an array field |
| jq ".users[] | .name" | Extract a field from every array element |
| jq -r .name | Raw 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 |
# 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.jsonJSON Schema Overview
JSON Schema is a vocabulary for validating the structure of JSON documents. It describes the expected shape, types, and constraints.
{
"$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
}| Keyword | Purpose |
|---|---|
| type | Expected data type (string, number, integer, boolean, object, array, null) |
| required | Array of required property names |
| properties | Define schema for each property |
| items | Schema for array elements |
| enum | Allowed values: ["red", "green", "blue"] |
| minimum / maximum | Numeric range constraints |
| minLength / maxLength | String length constraints |
| pattern | Regex pattern for strings |
| additionalProperties | Allow or deny extra keys (true/false or a schema) |
| oneOf / anyOf / allOf | Compose schemas with boolean logic |
| $ref | Reference another schema by URI |
Common Mistakes
Trailing commas
// INVALID - trailing comma after last element
{
"name": "Alice",
"age": 30,
}
// VALID
{
"name": "Alice",
"age": 30
}Single quotes instead of double quotes
// INVALID
{'name': 'Alice'}
// VALID
{"name": "Alice"}Comments
// INVALID - no comments allowed in JSON
{
// this is a comment
"name": "Alice" /* inline comment */
}
// VALID - no comments
{
"name": "Alice"
}Unquoted keys
// INVALID
{name: "Alice", age: 30}
// VALID
{"name": "Alice", "age": 30}Number precision issues
// 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.
| Format | Comments | Trailing Commas | Unquoted Keys | Single Quotes | Use Case |
|---|---|---|---|---|---|
| JSON | No | No | No | No | Data interchange, APIs, storage |
| JSONC | Yes (// and /**/) | Yes | No | No | VS Code settings, tsconfig.json |
| JSON5 | Yes (// and /**/) | Yes | Yes | Yes | Config 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.