Need help with your JSON?

Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool

JSON Formatter Cheat Sheets for Quick Reference

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It's easy for humans to read and write and easy for machines to parse and generate. Proper JSON formatting is crucial for readability, debugging, and ensuring data integrity when transferring information between systems. This cheat sheet provides a quick reference to JSON syntax rules and formatting techniques.

Basic JSON Syntax Rules

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array (usually denoted by {...}).
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence (usually denoted by [...]).

Objects

An object is an unordered set of name/value pairs.

{
  "key1": "value1",
  "key2": 123,
  "key3": true,
  "key4": null,
  "key5": {
    "nestedKey": "nestedValue"
  },
  "key6": [
    "arrayElement1",
    "arrayElement2"
  ]
}
  • Objects are enclosed in curly braces {}.
  • Name/value pairs are separated by a comma ,.
  • The name (key) and the value are separated by a colon :.
  • Keys must be strings enclosed in double quotes "".
  • Values can be a string, number, boolean, null, object, or array.

Arrays

An array is an ordered collection of values.

[
  "element1",
  123,
  false,
  {
    "type": "objectInArray"
  },
  [
    "nestedArray"
  ]
]
  • Arrays are enclosed in square brackets [].
  • Values are separated by a comma ,.
  • Values can be of any valid JSON data type (string, number, boolean, null, object, or array).

Values (Data Types)

A value must be one of the following JSON data types:

  • String: Sequence of zero or more Unicode characters, enclosed in double quotes "". Must be escaped correctly (e.g., \" for a double quote, \\ for a backslash, \n for newline, \r for carriage return, \t for tab, \f for form feed, \b for backspace, \uXXXX for Unicode characters).
    "Hello, World!"
    "String with a newline\nand a tab\t"
    "Contains a double quote: \""
    "Unicode character: \u20AC (Euro sign)"
  • Number: Integer or floating-point. Similar to JavaScript numbers, but NaN and Infinity are NOT valid JSON numbers.
    123
    -45.67
    1.2e+10
  • Boolean: true or false (lowercase).
    true
    false
  • Null: null (lowercase). Represents an empty or non-existent value.
    null
  • Object: As described above.
  • Array: As described above.

Whitespace

Whitespace (spaces, tabs, newlines, carriage returns) can be inserted between any two tokens. This is used for formatting and indentation to improve readability but is ignored by parsers. Formatted JSON adds whitespace for indentation. Minified JSON removes most non-essential whitespace.

Valid vs. Invalid JSON Syntax

Here are common mistakes that result in invalid JSON:

  • Trailing commas:
    { "key": "value", }
    Invalid
    [ 1, 2, 3, ]
    Invalid
  • Unquoted keys:
    { key: "value" }
    Invalid (key is not a string)
  • Single quotes for strings or keys:
    { 'key': 'value' }
    Invalid (both keys and string values need double quotes)
  • Comments:
    { "key": "value" // This is a comment }
    Invalid
  • Invalid number values: NaN, Infinity, -Infinity.
    { "number": NaN }
    Invalid
  • Incorrect boolean/null casing: TRUE, FALSE, NULL.
    { "boolean": TRUE }
    Invalid (must be lowercase true)

Using JSON.stringify() for Formatting

In JavaScript (and environments like Node.js), the built-in JSON.stringify() method is commonly used not only to convert a JavaScript object/value into a JSON string but also to format the output.

Syntax:

JSON.stringify(value[, replacer[, space]])

Parameters:

  • value: The JavaScript value to convert to a JSON string.
  • replacer (Optional): A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting the properties of thevalue object to be included in the JSON string. If null or not provided, all properties are included.
  • space (Optional): A String or Number object that's used to insert white space into the output JSON string for readability purposes.
    • If a Number, it indicates the number of space characters to use as white space for indentation (up to 10).
    • If a String, the string (or the first 10 characters of the string) is used as white space for indentation.
    • If not provided or null, no white space is used (minified output).

Formatting with Indentation

The space parameter is key for pretty-printing JSON.

Example: Using 2 spaces

const data = { name: "Alice", age: 30, city: "Wonderland" };
const formattedJson = JSON.stringify(data, null, 2);
// formattedJson will be:
/*
{
  "name": "Alice",
  "age": 30,
  "city": "Wonderland"
}
*/

Example: Using Tab character

const data = { name: "Alice", age: 30 };
const formattedJson = JSON.stringify(data, null, '\t');
// formattedJson will be:
/*
{
	"name": "Alice",
	"age": 30
}
*/

Filtering with Replacer (Array)

Use an array of keys as the replacer to include only specific properties.

const data = { name: "Alice", age: 30, city: "Wonderland", secret: "xyz" };
const keysToKeep = ["name", "age"];
const filteredJson = JSON.stringify(data, keysToKeep, 2);
// filteredJson will be:
/*
{
  "name": "Alice",
  "age": 30
}
*/

Transforming with Replacer (Function)

Use a function as the replacer to control how each key-value pair is stringified. The function receives the key and value and should return the value to be included, or undefined to omit the pair.

const data = { name: "Alice", age: 30, city: "Wonderland" };
const replacerFunction = (key, value) => {
  if (key === 'age') {
    return undefined; // Omit the age property
  }
  if (typeof value === 'string') {
    return value.toUpperCase(); // Convert strings to uppercase
  }
  return value; // Return other values unchanged
};
const transformedJson = JSON.stringify(data, replacerFunction, 2);
// transformedJson will be:
/*
{
  "name": "ALICE",
  "city": "WONDERLAND"
}
*/
// Note: The root key is an empty string when the replacer function is called for the top-level object.
// E.g., replacerFunction('', { name: "Alice", ... })

Quick Tips for Formatting & Debugging

  • Validate First: If you receive JSON from an external source and it fails parsing, use an online JSON validator/formatter immediately. It will highlight syntax errors precisely.
  • Use Editor Extensions: Most modern code editors (VS Code, Sublime Text, etc.) have extensions for JSON that provide syntax highlighting, validation, and automatic formatting on save.
  • Browser Developer Tools: Browser consoles often print JSON objects interactively, allowing you to expand and inspect them easily, which helps in visualizing structured data.
  • Command Line Tools: Tools like jq are incredibly powerful for formatting, slicing, filtering, and transforming JSON data directly from the command line. Example: cat data.json | jq . will pretty-print the JSON.
  • Understand JSON.parse(): This method converts a JSON string into a JavaScript object or value. Formatting applies to creating the string (`stringify`), not parsing it (`parse`).
    const jsonString = '{"name": "Alice"}';
    const jsObject = JSON.parse(jsonString); // jsObject is { name: "Alice" }
    

Mastering JSON formatting ensures your data is always clean, readable, and correctly structured, making your development workflow smoother and debugging less painful.

Need help with your JSON?

Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool