JSON Formatting and Validation - The Complete Guide 2026

What Is JSON

JSON, which stands for JavaScript Object Notation, is a lightweight data interchange format that has become the standard for transmitting structured data across the web. Douglas Crockford popularized the format in the early 2000s, and it is now defined by two standards: ECMA-404 and RFC 8259. Despite having "JavaScript" in its name, JSON is language-independent and is supported natively by virtually every modern programming language.

JSON emerged as a simpler alternative to XML for data exchange. Where XML requires opening and closing tags, attributes, and namespaces, JSON uses a minimal syntax of curly braces, square brackets, colons, and commas. This simplicity makes JSON easier to read, write, and parse. Today, JSON is the dominant format for REST APIs, configuration files, NoSQL databases like MongoDB and CouchDB, and data storage in web applications.

The format is built on two universal data structures that exist in some form in every programming language: a collection of name/value pairs (realized as an object, dictionary, or hash table) and an ordered list of values (realized as an array, list, or vector). This universality is what makes JSON so effective as an interchange format. Data serialized as JSON on a Python server can be deserialized on a JavaScript client without any ambiguity about the structure.

To format and validate your JSON data right now, use our JSON Formatter tool, which provides instant formatting, syntax highlighting, and error detection.

JSON Syntax Rules

JSON has a deliberately small set of syntax rules. Understanding these rules completely will prevent the vast majority of formatting errors you encounter. Here is the complete set of rules that define valid JSON:

A JSON document must contain a single root value. That root value can be an object, an array, a string, a number, a boolean, or null. Most practical JSON documents use an object or array as the root value, but a standalone string like "hello" or a number like 42 is technically valid JSON.

Objects are enclosed in curly braces {}. An object contains zero or more name/value pairs (also called properties or members). Each name must be a string enclosed in double quotes. The name and value are separated by a colon. Multiple pairs are separated by commas. The order of pairs in an object is not significant, meaning parsers are not required to preserve insertion order, though most implementations do.

{
  "name": "Alice",
  "age": 30,
  "email": "[email protected]"
}

Arrays are enclosed in square brackets []. An array contains zero or more values separated by commas. Values in an array do not need to be the same type. An array can contain strings, numbers, objects, other arrays, booleans, and null values all mixed together, though uniform arrays are more common in practice.

[
  "apple",
  42,
  true,
  null,
  {"key": "value"},
  [1, 2, 3]
]

Strings must be enclosed in double quotes. Single quotes are not valid in JSON. Strings can contain any Unicode character except the control characters that must be escaped. The following escape sequences are supported: \" for a double quote, \\ for a backslash, \/ for a forward slash, \b for backspace, \f for form feed, \n for newline, \r for carriage return, \t for tab, and \uXXXX for a Unicode code point.

There must be no trailing comma after the last item in an object or array. This is one of the most common sources of JSON errors, especially for developers coming from JavaScript where trailing commas are permitted.

Important: JSON does not support comments. There is no syntax for single-line or multi-line comments. If you try to include // or /* */ comments, the JSON will be invalid and parsers will reject it.

JSON Data Types

JSON supports exactly six data types. Understanding the boundaries of each type is important for writing valid JSON and avoiding subtle bugs when parsing data.

String

A sequence of zero or more Unicode characters wrapped in double quotes. Strings are the most common data type in JSON. Keys in objects are always strings. Remember that only double quotes are valid. Single quotes, backticks, and unquoted strings will cause parse errors.

{
  "greeting": "Hello, World",
  "empty": "",
  "escaped": "Line one\nLine two",
  "unicode": "Caf\u00e9"
}

Number

JSON numbers can be integers or floating-point values. They support optional negative signs and scientific notation with e or E. Numbers must not have leading zeros (except for 0 itself and decimals like 0.5). JSON does not support the special values Infinity, -Infinity, or NaN. If you need to represent these, use a string or null instead. JSON does not distinguish between integer and floating-point types. The number 1 and the number 1.0 are both valid JSON numbers, and the parser decides how to represent them internally.

{
  "integer": 42,
  "negative": -17,
  "float": 3.14159,
  "scientific": 2.998e8,
  "zero": 0
}

Boolean

The literal values true and false, written in lowercase without quotes. Using True, FALSE, or any other capitalization is invalid. Wrapping them in quotes makes them strings, not booleans.

Null

The literal value null, written in lowercase without quotes. Null represents the intentional absence of a value. It is different from an empty string "", the number 0, or the boolean false. Using None, nil, undefined, or NULL is invalid.

Object

An unordered collection of name/value pairs enclosed in curly braces. Objects can be nested to any depth. Each key within a single object should be unique. The JSON specification states that keys "should" be unique but does not strictly forbid duplicates. However, behavior with duplicate keys is undefined, and different parsers handle them differently. Some keep the first occurrence, some keep the last, and some reject the document entirely. Always use unique keys.

Array

An ordered sequence of values enclosed in square brackets. Arrays preserve insertion order and are zero-indexed in most programming languages. Like objects, arrays can be nested to any depth and can contain mixed types.

Formatting and Pretty Printing JSON

JSON formatting, also called pretty printing or beautifying, is the process of adding whitespace (spaces, tabs, and newlines) to a JSON string to make it human-readable. The JSON specification treats all whitespace between tokens as insignificant, meaning a minified single-line JSON string and a pretty-printed multi-line version represent exactly the same data.

Pretty printing is essential during development and debugging. Consider the difference between these two representations of the same data:

Minified JSON

{"users":[{"id":1,"name":"Alice","roles":["admin","editor"]},{"id":2,"name":"Bob","roles":["viewer"]}]}

Pretty Printed JSON (2-space indentation)

{
  "users": [
    {
      "id": 1,
      "name": "Alice",
      "roles": [
        "admin",
        "editor"
      ]
    },
    {
      "id": 2,
      "name": "Bob",
      "roles": [
        "viewer"
      ]
    }
  ]
}

Both versions are valid JSON containing identical data. The pretty-printed version is dramatically easier to read, understand, and debug. Most formatting tools let you choose the indentation level: 2 spaces, 4 spaces, or tabs. Two spaces is the most common convention in JavaScript and web development. Four spaces is more common in Python ecosystems. Tabs allow each developer to set their preferred visual width.

Most programming languages provide built-in JSON formatting. In JavaScript, JSON.stringify(data, null, 2) produces pretty-printed output with 2-space indentation. In Python, json.dumps(data, indent=2) does the same. On the command line, you can pipe JSON through python -m json.tool or jq . to format it.

For quick formatting without writing code, our JSON Formatter provides instant pretty printing with customizable indentation, along with syntax highlighting that makes the structure even easier to follow.

JSON Minification

JSON minification is the opposite of pretty printing. It removes all insignificant whitespace from a JSON string, producing the most compact representation possible. Minification reduces the byte size of JSON data, which matters for network transfer and storage.

The size reduction from minification varies depending on the original formatting and the depth of nesting. A deeply nested JSON document with 4-space indentation might shrink by 30% to 50% when minified. A moderately nested document with 2-space indentation typically shrinks by 15% to 25%.

In most programming languages, producing minified JSON is the default behavior. JavaScript's JSON.stringify(data) without the third argument produces minified output. Python's json.dumps(data, separators=(',', ':')) uses the most compact separators, removing the spaces after colons and commas that the default includes.

Minification should be applied to all JSON sent over the network in production. API responses, configuration fetched by clients, and JSON payloads stored in databases should all be minified. The whitespace in pretty-printed JSON is purely for human convenience and provides no value to machines. When combined with HTTP compression (gzip or Brotli), minified JSON produces the smallest possible payload.

Tip: During development, configure your API framework to pretty-print responses when a debug flag is present (such as ?pretty=true in the query string) and minify by default in production. This gives you readable output during development without any production overhead.

Validating JSON

JSON validation checks whether a string conforms to the JSON syntax rules. A valid JSON string can be parsed without errors by any compliant JSON parser. Validation catches syntax errors like missing commas, mismatched brackets, and invalid escape sequences before the data reaches your application logic.

There are two levels of JSON validation:

Syntax validation checks whether the string is well-formed JSON. This is the most basic level. Any JSON parser performs syntax validation during parsing, and will throw an error if the input is not valid. You can validate JSON syntax in JavaScript by wrapping JSON.parse() in a try/catch block. If parsing succeeds, the JSON is syntactically valid.

function isValidJSON(str) {
  try {
    JSON.parse(str);
    return true;
  } catch (e) {
    return false;
  }
}

Structural validation (also called schema validation) checks whether the parsed JSON data conforms to an expected structure. For example, you might require that an object has a "name" field of type string, an "age" field of type number, and an optional "email" field. Structural validation is performed using JSON Schema, which we cover in the next section.

Common JSON validation workflows include validating API request bodies before processing them, checking configuration files at application startup, verifying data integrity before storing JSON in a database, and validating JSON output from code generators or templates.

For quick validation of JSON snippets, use our JSON Formatter which highlights syntax errors with clear messages indicating the line number and type of error. For navigating complex JSON structures, our JSON Viewer provides a tree view that makes it easy to explore deeply nested data.

Common JSON Errors and How to Fix Them

Certain JSON errors come up repeatedly. Knowing them saves significant debugging time. Here are the errors that developers encounter most frequently, along with how to identify and fix each one.

Trailing Commas

A trailing comma after the last element in an object or array is the single most common JSON error. JavaScript, Python, and many other languages allow trailing commas. JSON does not.

// Invalid: trailing comma after "email"
{
  "name": "Alice",
  "age": 30,
  "email": "[email protected]",
}

// Valid: no trailing comma
{
  "name": "Alice",
  "age": 30,
  "email": "[email protected]"
}

Single Quotes

JSON requires double quotes for strings. Single quotes are invalid. This is a frequent error for Python developers (where single and double quotes are interchangeable) and JavaScript developers (where both are also valid).

// Invalid: single quotes
{'name': 'Alice'}

// Valid: double quotes
{"name": "Alice"}

Unquoted Keys

All object keys in JSON must be double-quoted strings. JavaScript allows unquoted keys in object literals if they are valid identifiers, but JSON does not.

// Invalid: unquoted key
{name: "Alice"}

// Valid: quoted key
{"name": "Alice"}

Comments

JSON does not support comments. Any line starting with // or block delimited by /* and */ will cause a parse error. If you are editing a configuration file that looks like JSON but supports comments, it is likely JSONC (JSON with Comments), which is a non-standard extension used by editors like VS Code.

Special Number Values

JSON does not support Infinity, -Infinity, NaN, or hexadecimal numbers like 0xFF. If your application produces these values, serialize them as strings or null before encoding to JSON.

// Invalid
{"value": NaN, "max": Infinity}

// Valid alternatives
{"value": null, "max": "Infinity"}
{"value": null, "max": 1.7976931348623157e+308}

Unescaped Control Characters

Control characters (Unicode code points U+0000 through U+001F) must be escaped in JSON strings. The most common offender is a literal tab character or newline embedded in a string instead of the escape sequences \t and \n.

Missing or Extra Brackets

Mismatched curly braces or square brackets cause parse errors. In deeply nested JSON, it can be difficult to spot the missing bracket. A good JSON formatter will highlight the mismatch and indicate where the parser expected the closing bracket.

Tip: When you encounter a JSON parse error, paste your JSON into a JSON Formatter that reports error locations. The error message will typically include the line number and character position where parsing failed, along with a description like "expected comma or closing brace."

JSON Schema for Structural Validation

JSON Schema is a vocabulary that lets you describe the expected structure and content of JSON data. It is itself expressed as JSON, which makes it easy to read, write, and process programmatically. JSON Schema is defined in a series of IETF drafts, with the 2020-12 specification being the latest stable version.

A JSON Schema defines the type of each field, required fields, allowed values, minimum and maximum constraints, string patterns (regular expressions), array length constraints, and more. Here is a simple schema for a user object:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "name": {
      "type": "string",
      "minLength": 1,
      "maxLength": 100
    },
    "age": {
      "type": "integer",
      "minimum": 0,
      "maximum": 150
    },
    "email": {
      "type": "string",
      "format": "email"
    },
    "roles": {
      "type": "array",
      "items": {
        "type": "string",
        "enum": ["admin", "editor", "viewer"]
      },
      "minItems": 1,
      "uniqueItems": true
    }
  },
  "required": ["name", "email"]
}

JSON Schema is widely used for API documentation (OpenAPI/Swagger uses JSON Schema to describe request and response bodies), form validation, configuration file validation, and data pipeline integrity checks. Libraries for JSON Schema validation exist in every major language, including Ajv for JavaScript, jsonschema for Python, and json-schema for Ruby.

Querying JSON with JSONPath

JSONPath is a query language for extracting specific values from a JSON document. It works similarly to XPath for XML. JSONPath expressions describe a path through the JSON structure to the values you want to retrieve.

The syntax uses dot notation or bracket notation to navigate through the structure:

// Given this JSON:
{
  "store": {
    "books": [
      {"title": "The Great Gatsby", "price": 12.99},
      {"title": "1984", "price": 9.99},
      {"title": "Dune", "price": 14.99}
    ]
  }
}

// JSONPath expressions:
$.store.books[0].title     // "The Great Gatsby"
$.store.books[*].title     // All book titles
$.store.books[[email protected]<10] // Books under $10
$.store.books[-1]          // Last book (Dune)

JSONPath is invaluable when working with large JSON documents where you need to extract specific pieces of data without navigating the entire structure manually. It is supported by many programming languages and tools, including jq for the command line, which uses a similar but slightly different syntax.

To test JSONPath expressions against your data, use our JSON Path Finder tool, which lets you paste a JSON document and interactively build and test path expressions.

JSON Alternatives and When to Use Them

YAML

YAML is a superset of JSON that adds features like comments, multi-line strings, anchors and aliases (references), and a more human-readable syntax that uses indentation instead of braces. YAML is popular for configuration files (Docker Compose, Kubernetes manifests, CI/CD pipelines) where human readability is a priority. The downside is that YAML's whitespace-sensitivity can lead to subtle bugs, and the specification is significantly more complex than JSON's.

To convert between JSON and YAML, use our JSON to YAML Converter tool, which handles the conversion in both directions with proper formatting.

CSV

CSV (Comma-Separated Values) is the simplest tabular data format. It works well for flat, table-like data (spreadsheets, database exports) but cannot represent nested structures. JSON is better for hierarchical data, while CSV is better for flat datasets where each row has the same columns.

When you need to transform spreadsheet data into JSON format for an API or application, our CSV to JSON Converter handles the conversion cleanly, mapping CSV columns to JSON object keys.

XML

XML predates JSON and offers features like namespaces, schemas (XSD), transformations (XSLT), and attributes. XML is still widely used in enterprise systems, SOAP web services, and document formats (HTML, SVG, RSS). For new projects, JSON is generally preferred for data interchange due to its simpler syntax and smaller payload size, but XML remains relevant in many domains.

Protocol Buffers and MessagePack

For performance-critical applications, binary serialization formats like Protocol Buffers (protobuf), MessagePack, and CBOR offer smaller payloads and faster parsing than JSON. They sacrifice human readability for efficiency. These formats are common in microservice communication, real-time systems, and mobile applications where bandwidth and CPU are constrained.

Working with JSON in Programming Languages

JavaScript

// Parse JSON string to object
const data = JSON.parse('{"name": "Alice", "age": 30}');

// Serialize object to JSON string
const json = JSON.stringify(data);

// Pretty print with 2-space indentation
const pretty = JSON.stringify(data, null, 2);

// Custom serialization with replacer function
const filtered = JSON.stringify(data, (key, value) => {
  if (key === 'password') return undefined; // omit passwords
  return value;
}, 2);

// Parse with reviver function (transform during parsing)
const withDates = JSON.parse(jsonStr, (key, value) => {
  if (key === 'createdAt') return new Date(value);
  return value;
});

Python

import json

# Parse JSON string to dict
data = json.loads('{"name": "Alice", "age": 30}')

# Serialize dict to JSON string
json_str = json.dumps(data)

# Pretty print
pretty = json.dumps(data, indent=2, sort_keys=True)

# Read JSON from file
with open('data.json', 'r') as f:
    data = json.load(f)

# Write JSON to file
with open('output.json', 'w') as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

Command Line with jq

# Pretty print JSON
echo '{"name":"Alice","age":30}' | jq .

# Extract a specific field
echo '{"name":"Alice","age":30}' | jq '.name'

# Filter array elements
echo '[1,2,3,4,5]' | jq '[.[] | select(. > 3)]'

# Transform JSON structure
cat data.json | jq '{user: .name, years: .age}'

JSON Best Practices

Following consistent conventions when working with JSON improves code readability, reduces errors, and makes APIs easier to consume. Here are practices that have proven valuable across large-scale production systems.

Use consistent key naming. The most common convention in web APIs is camelCase (firstName, emailAddress). Some APIs use snake_case (first_name, email_address), which is more natural in Python and Ruby ecosystems. Pick one convention and apply it consistently throughout your API. Never mix conventions within the same API.

Keep nesting depth reasonable. While JSON supports arbitrary nesting depth, deeply nested structures (more than 4 to 5 levels) are difficult to work with and often indicate a design problem. If you find yourself creating deeply nested JSON, consider flattening the structure or breaking it into separate endpoints.

Use arrays for ordered collections and objects for named properties. Do not use an object with numeric string keys ({"0": "first", "1": "second"}) when an array (["first", "second"]) is more appropriate. Objects are for key-value mappings where the keys are meaningful names.

Handle null consistently. Decide whether missing optional fields should be omitted entirely or included with a null value, and apply that decision uniformly. Omitting null fields reduces payload size. Including them makes the schema more explicit and avoids bugs where code does not check for the existence of a key.

Validate at boundaries. Parse and validate JSON at the entry points of your system: API request handlers, file readers, and message consumers. Do not pass raw JSON strings through your application. Parse early, validate against a schema, and work with typed objects internally.

Tip: When debugging JSON issues, use a dedicated viewer rather than reading raw text. Our JSON Viewer renders JSON as a collapsible tree with syntax highlighting, making it easy to navigate large documents and spot structural problems.

Frequently Asked Questions

JSON is a text-based data format with strict syntax rules. JavaScript objects are in-memory data structures in the JavaScript language. JSON requires all keys to be double-quoted strings and does not support functions, undefined, comments, or trailing commas. A JavaScript object can use unquoted keys, single-quoted strings, and include any JavaScript expression as a value. JSON is a subset of the JavaScript object literal syntax, but they are not the same thing.

The most common reasons for invalid JSON are: trailing commas after the last item in an array or object, single quotes instead of double quotes around strings, unquoted property names, comments (JSON does not support comments), using undefined or NaN as values, and missing commas between items. Use a JSON validator to pinpoint the exact location and type of error in your data.

The JSON specification does not define a maximum size. The practical limit depends on the system processing the JSON. Most programming languages can handle JSON files of several hundred megabytes. Web APIs commonly limit request body size to 1 MB to 10 MB. Browsers can parse JSON strings of hundreds of megabytes, though performance degrades with very large files. For datasets exceeding a few hundred megabytes, consider streaming JSON parsers or alternative formats like JSON Lines.

Yes, minifying JSON for production API responses is generally recommended. Minified JSON removes unnecessary whitespace, reducing the payload size. Combined with gzip or Brotli compression on the server, this provides the smallest possible response. However, during development, pretty-printed JSON is much easier to read and debug. Many API frameworks support a query parameter like ?pretty=true to toggle between formats.

No. The JSON specification (RFC 8259) does not support comments of any kind. Neither single-line comments nor block comments are valid in JSON. If you need a configuration format with comments, consider JSON5, JSONC (JSON with Comments, used by VS Code), YAML, or TOML. Some parsers offer a non-standard option to strip comments before parsing, but the resulting data is technically not valid JSON.

Wikipedia

JSON (JavaScript Object Notation) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects.

Source: Wikipedia - JSON · Verified March 20, 2026

Stack Overflow Community

3421How to pretty print JSON1876JSON.parse vs JSON.stringify987Validating JSON in JavaScript

Video Tutorials

▶ Watch related tutorials on YouTube

Quick Facts

Data Types
6
Created
2001
RFC
8259
MIME
application/json

Update History

March 20, 2026 - Article published with comprehensive coverage
March 19, 2026 - Research and drafting completed

Browser Compatibility

Chrome 90+ Firefox 88+ Safari 14+ Edge 90+ Opera 76+

Last Updated: March 20, 2026