Quick Answer
JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format. It is the dominant format for web APIs, configuration files, and structured data exchange between systems. If you work with web development, APIs, or data pipelines, you will work with JSON daily.
What JSON Is and Where It Comes From
JSON was derived from JavaScript object literal syntax, but it is language-independent. It was specified by Douglas Crockford in the early 2000s and standardized as ECMA-404 and RFC 8259. Despite its JavaScript origins, JSON is supported natively in virtually every modern programming language.
JSON has largely replaced XML as the default data interchange format for web APIs because it is simpler to read, write, and parse. It has fewer rules, less syntactic overhead, and maps directly to native data structures in most languages.
JSON Syntax Rules
JSON is strict. Unlike JavaScript object literals, JSON does not tolerate shortcuts. The complete set of rules is small but non-negotiable:
| Rule | Valid | Invalid |
|---|---|---|
| Keys must be double-quoted strings | {"name": "Alice"} |
{name: "Alice"} |
| Strings must use double quotes | "hello" |
'hello' |
| No trailing commas | {"a": 1} |
{"a": 1,} |
| No comments | {"a": 1} |
{"a": 1 // note} |
| No undefined or NaN | {"a": null} |
{"a": undefined} |
| Numbers cannot have leading zeros | {"id": 42} |
{"id": 042} |
JSON Data Types
JSON supports exactly six data types, and nothing else:
| Type | Example | Notes |
|---|---|---|
| String | "hello world" |
Must use double quotes. Supports Unicode escapes. |
| Number | 42, 3.14, -1, 1e10 |
No distinction between integer and float. No hex, octal, or Infinity. |
| Boolean | true, false |
Lowercase only. True or TRUE are invalid. |
| Null | null |
Represents absence of value. Lowercase only. |
| Object | {"key": "value"} |
Unordered set of key-value pairs. Keys must be unique strings. |
| Array | [1, "two", null] |
Ordered list. Can contain mixed types. |
Parsing JSON in Different Languages
JavaScript
// Parse a JSON string
const data = JSON.parse('{"name": "Alice", "age": 30}');
console.log(data.name); // "Alice"
// Serialize an object to JSON
const json = JSON.stringify(data, null, 2);
console.log(json);
// Safe parsing with error handling
function safeParse(text) {
try {
return { data: JSON.parse(text), error: null };
} catch (e) {
return { data: null, error: e.message };
}
}
Python
import json
# Parse a JSON string
data = json.loads('{"name": "Alice", "age": 30}')
print(data["name"]) # "Alice"
# Serialize to formatted JSON
output = json.dumps(data, indent=2, ensure_ascii=False)
print(output)
# Parse from a file
with open("data.json", "r") as f:
data = json.load(f)
Go
import "encoding/json"
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
// Parse JSON into a struct
var user User
err := json.Unmarshal([]byte(jsonString), &user)
// Serialize to JSON
output, err := json.MarshalIndent(user, "", " ")
The JSON Workflow: Format, Validate, Minify
Working with JSON typically involves three distinct operations, and using the right one at the right time prevents confusion:
- Validate first if the JSON might be broken. Use the JSON Validator to find syntax errors and get exact line and character positions.
- Format for readability once the JSON is valid. The JSON Formatter adds indentation and line breaks so you can inspect nested structures.
- Minify for production when you need compact output. The JSON Minifier strips all whitespace for smaller payloads.
Common JSON Errors and How to Fix Them
Most JSON parse failures come from a small set of recurring mistakes. The fix is almost always the same: find the first error, fix it, and re-validate.
| Error | Cause | Fix |
|---|---|---|
| Unexpected token | Single quotes, unquoted keys, or comments | Use double quotes, remove comments |
| Unexpected end of input | Missing closing bracket or brace | Count opening and closing delimiters |
| Unexpected comma | Trailing comma after last item | Remove the trailing comma |
| Duplicate key warning | Same key used twice in one object | Rename or remove the duplicate |
For a detailed walkthrough of each error type with language-specific error messages, see the JSON parse errors guide.
JSON Schema Validation
JSON Schema is a vocabulary that lets you annotate and validate the structure of JSON documents. While basic JSON validation checks syntax, schema validation checks whether the data conforms to an expected structure: required fields, value types, string formats, number ranges, and array lengths.
Schema validation is essential for API contracts. It catches problems like missing required fields, wrong data types, and out-of-range values before they cause downstream failures. Tools like AJV (JavaScript), jsonschema (Python), and everit-org (Java) implement JSON Schema validation.
JSON Alternatives: JSON5, JSONC, and YAML
Strict JSON is sometimes too rigid for configuration files where comments and trailing commas improve maintainability. Several relaxed alternatives exist:
| Format | Allows comments | Allows trailing commas | Common use |
|---|---|---|---|
| JSON | No | No | APIs, data exchange |
| JSON5 | Yes | Yes | Config files, developer tools |
| JSONC | Yes (// and /* */) | Yes | VS Code settings, TypeScript config |
| YAML | Yes | N/A (no commas) | CI/CD configs, Kubernetes manifests |
Remember: these formats are not valid JSON. If an API expects JSON, send strict JSON. Use relaxed formats only where the parser explicitly supports them.
Working with Large JSON Files
Standard JSON parsers load the entire document into memory before processing. For multi-megabyte or multi-gigabyte JSON files, this can cause out-of-memory errors. Streaming parsers solve this by processing the document incrementally:
- JavaScript: Use libraries like
JSONStreamorstream-jsonfor Node.js streaming. - Python: Use
ijsonfor iterative parsing of large JSON files without loading them entirely. - Command line:
jqhandles large files efficiently and supports streaming mode.
For browser-based work with moderately large payloads, the JSON Formatter processes data locally without uploading, but extremely large files (100MB+) may exceed browser memory limits.
JSON in API Debugging
When an API returns unexpected results, the debugging workflow typically follows this pattern:
- Capture the raw response (browser DevTools Network tab, curl, or Postman).
- Validate the response to ensure it is syntactically correct JSON.
- Format the response for human inspection.
- Compare against the expected schema or previous known-good responses using the Structured Data Diff.
- If the response is a JWT or contains encoded tokens, decode them with the JWT Decoder.
Converting Between JSON and Other Formats
JSON rarely exists in isolation. Data flows between CSV spreadsheets, XML legacy systems, TypeScript interfaces, and other formats:
- CSV to JSON: Use the CSV JSON Converter when importing spreadsheet data into web applications.
- XML to JSON: Use the XML JSON Converter when integrating with legacy SOAP APIs or XML-based configurations.
- JSON to TypeScript: Use the JSON to TypeScript Generator to create type-safe interfaces from API response samples.
See the data format conversion guide for detailed strategies on handling nested data, type coercion, and delimiter edge cases.
FAQ
Is JSON the same as a JavaScript object?
No. JSON is stricter: keys must be double-quoted, only double-quoted strings are allowed, and comments, trailing commas, and undefined values are forbidden. A JavaScript object literal is more permissive.
Can JSON contain binary data?
Not directly. Binary data must be encoded as a string, typically using Base64. The Base64 Encoder can help with this conversion.
What is the maximum size of a JSON document?
The JSON specification does not define a size limit. Practical limits depend on the parser, available memory, and transport layer. Most web APIs limit request bodies to a few megabytes.
Should I use JSON or YAML for configuration files?
Use JSON when strict parsing and broad tooling support matter. Use YAML when human editability and comments are important. For VS Code and TypeScript configs, JSONC (JSON with comments) is often the best choice.
How do I handle dates in JSON?
JSON has no native date type. The most common convention is ISO 8601 strings (e.g., "2026-04-13T10:30:00Z"). Unix timestamps as numbers are also widely used. Choose one format and be consistent.
Why does JSON not allow comments?
Douglas Crockford intentionally excluded comments to prevent their misuse as parsing directives, which had caused interoperability problems in other formats. If you need comments, use JSON5 or JSONC where supported.
Related Tools
- JSON Formatter for readable output from valid JSON
- JSON Validator for finding syntax errors
- JSON Minifier for compact production output
- CSV JSON Converter for tabular data conversion
- XML JSON Converter for legacy format integration
- JSON to TypeScript Generator for type-safe interfaces
- Structured Data Diff for comparing JSON documents