What Is JSON?
Learn JSON syntax, data types, nested objects, arrays, and the real-world places JSON appears.
Read guide →Guides for formatting, validating, fixing, and understanding JSON.
Start with the basics of JSON, then move into API response formatting, invalid JSON repair, AI-generated JSON cleanup, debugging, comparing files, and quick-reference material. These guides are written for developers, testers, students, and anyone who needs to work with JSON.
These four guides take you from zero to confidently working with JSON in APIs and code:
Skip ahead to the guides that match where you are:
Learn JSON syntax, data types, nested objects, arrays, and the real-world places JSON appears.
Read guide →Understand pretty-printing, minification, indentation, readability, and when each format is best.
Read guide →Fix trailing commas, missing quotes, invalid escapes, mismatched brackets, and other frequent parse errors.
Read guide →Beautify, validate, inspect, compare, and export JSON responses copied from REST APIs, logs, curl, Postman, or browser DevTools.
Read guide →Learn how to repair trailing commas, single quotes, unquoted keys, comments, and other invalid JSON syntax problems.
Read guide →Understand what unexpected token errors mean, why they happen, and how to find the broken character quickly.
Read guide →Clean and validate JSON copied from ChatGPT, Claude, Cursor, Codex, and other AI tools without claiming the formatter is AI-powered.
Read guide →Compare JSON and XML syntax, use cases, readability, ecosystem support, and API design tradeoffs.
Read guide →Learn practical ways to compare JSON files, review API changes, and spot differences in nested data.
Read guide →Answers to common questions about JSON syntax, validation, formatting, privacy, export, and loading data.
Read FAQ →A bookmark-friendly reference for JSON syntax, values, escaping, examples, and common mistakes.
Open cheatsheet →JSON is built from two structures: objects (key-value pairs inside curly braces {}) and arrays (ordered lists inside square brackets []). Values can be strings, numbers, booleans, null, nested objects, or arrays.
{
"user": {
"id": 42,
"name": "Deepak Kumar",
"active": true,
"roles": ["admin", "developer"],
"address": null
}
}
The guide What Is JSON? walks through every part of this syntax in detail, including data types, nesting rules, and real-world examples.
JSON is the standard data format for REST APIs, configuration files, browser storage (localStorage), NoSQL databases, and data exchange between services. If a web app talks to a server, that exchange is almost certainly in JSON.
No, though the syntax looks similar. A JavaScript object can have functions, comments, and unquoted keys. JSON is stricter: all keys must be double-quoted strings, values must be one of six types, and there are no comments or trailing commas allowed. Use JSON.parse() to convert a JSON string into a JavaScript object and JSON.stringify() to convert back.
The most common causes are a trailing comma after the last item in an object or array, single quotes instead of double quotes around keys or strings, an unquoted key, a comment left inside the JSON, or a missing or extra bracket. Paste your JSON into the formatter to see the exact line and character where the problem is.
No. Standard JSON does not allow comments. If you need comments in a config file, look at JSONC (used in VS Code settings) or JSON5. To use those formats with a standard parser, strip the comments first.
Pretty-printed JSON adds indentation and line breaks so humans can read it easily. Minified JSON strips all unnecessary whitespace to reduce file size. Use pretty-printed when debugging or reviewing data; use minified when sending data over the network. The JSON Formatter Hub switches between both formats instantly.
Every value in JSON must be one of exactly six types. Knowing these types is the single most important thing to understand before working with any JSON data.
Any text wrapped in double quotes. Strings can contain letters, numbers, spaces, and special characters. Single quotes are not allowed — only double quotes are valid in JSON.
"name": "Deepak Kumar"
"city": "New Delhi"
"message": "Hello, World!"
Any integer or decimal number. No quotes around it. JSON does not distinguish between integers and floats — both are just "number". Very large or very small numbers can use scientific notation.
"age": 28
"price": 99.99
"temperature": -12.5
"distance": 1.5e10
Exactly two possible values: true or false. Both must be lowercase — True or FALSE will cause a parse error.
"isActive": true
"isDeleted": false
Represents the intentional absence of a value. Must be written as lowercase null. Useful for fields that exist in a schema but have no value yet, like an optional phone number or an unset expiry date.
"middleName": null
"deletedAt": null
A collection of key-value pairs wrapped in curly braces {}. Keys must be strings (double-quoted). Values can be any of the six JSON types, including another object. Objects can nest as deeply as needed.
"address": {
"street": "12 MG Road",
"city": "Bangalore",
"pincode": "560001"
}
An ordered list of values wrapped in square brackets []. Items are separated by commas. An array can contain any mix of types — strings, numbers, objects, even other arrays.
"tags": ["javascript", "api", "tutorial"]
"scores": [98, 87, 74, 91]
"users": [
{ "id": 1, "name": "Priya" },
{ "id": 2, "name": "Rahul" }
]
JSON has a strict set of rules. Even one small mistake makes the entire document invalid. These are the rules you must follow:
{ name: "Priya" } is invalid. { "name": "Priya" } is correct.{ "a": 1, } is invalid.// this is a comment and /* block comment */ are both illegal inside JSON.'hello' are not valid JSON."age": "28" makes age a string, not a number.True, False, NULL are all invalid.{ needs a matching }. Every [ needs a matching ].Here is a side-by-side example of invalid and valid JSON:
// INVALID JSON
{
name: 'Priya', // unquoted key, single-quoted value
age: 25, // trailing comma after last item
active: True, // boolean must be lowercase
// this is a comment // comments not allowed
}
// VALID JSON
{
"name": "Priya",
"age": 25,
"active": true
}
In JavaScript (and most other languages), JSON is always handled as a string when it travels over the network or gets stored. You must convert it to a usable object before you can work with its values.
Use JSON.parse() any time you receive JSON from an API, read it from a file, or load it from localStorage.
const jsonString = '{"name":"Priya","age":25,"roles":["admin","editor"]}';
const user = JSON.parse(jsonString);
console.log(user.name); // "Priya"
console.log(user.age); // 25
console.log(user.roles[0]); // "admin"
Use JSON.stringify() any time you want to send data to an API, save it to localStorage, or write it to a file. The optional second and third arguments control filtering and indentation.
const user = { name: "Priya", age: 25, roles: ["admin", "editor"] };
// compact (for sending over the network)
const compact = JSON.stringify(user);
// '{"name":"Priya","age":25,"roles":["admin","editor"]}'
// pretty-printed (for logging or saving to a file)
const pretty = JSON.stringify(user, null, 2);
// {
// "name": "Priya",
// "age": 25,
// "roles": [
// "admin",
// "editor"
// ]
// }
Use dot notation for known keys and bracket notation for dynamic keys or keys that contain special characters.
const data = {
"order": {
"id": 1042,
"customer": { "name": "Rahul", "city": "Mumbai" },
"items": [
{ "product": "Keyboard", "qty": 1 },
{ "product": "Mouse", "qty": 2 }
]
}
};
console.log(data.order.id); // 1042
console.log(data.order.customer.name); // "Rahul"
console.log(data.order.items[0].product); // "Keyboard"
console.log(data.order.items[1].qty); // 2
The Fetch API is the modern way to make HTTP requests in JavaScript. Every response from a REST API is JSON, and response.json() parses it automatically — no JSON.parse() needed.
fetch('https://api.example.com/users/42')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // parses the JSON body
})
.then(user => {
console.log(user.name); // use the data
})
.catch(error => {
console.error('Fetch failed:', error);
});
async function getUser(id) {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) throw new Error(`HTTP error: ${response.status}`);
const user = await response.json();
return user;
}
const user = await getUser(42);
console.log(user.name);
When sending JSON to a server, set the Content-Type header to application/json and use JSON.stringify() to convert your object into a string body.
async function createUser(data) {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
return await response.json();
}
const newUser = await createUser({ name: "Priya", role: "admin" });
console.log(newUser.id); // server-assigned ID
Python's built-in json module handles everything you need. The two main functions mirror JavaScript: json.loads() parses a JSON string into a Python dict, and json.dumps() converts a dict back into a JSON string.
import json
json_string = '{"name": "Priya", "age": 25, "roles": ["admin", "editor"]}'
# parse string into a Python dict
user = json.loads(json_string)
print(user["name"]) # Priya
print(user["age"]) # 25
print(user["roles"][0]) # admin
import json
user = {"name": "Priya", "age": 25, "roles": ["admin", "editor"]}
# compact (for sending over HTTP)
compact = json.dumps(user)
# '{"name": "Priya", "age": 25, "roles": ["admin", "editor"]}'
# pretty-printed (for saving to a file or logging)
pretty = json.dumps(user, indent=2)
# {
# "name": "Priya",
# "age": 25,
# "roles": [
# "admin",
# "editor"
# ]
# }
import json
# read a JSON file
with open("users.json", "r") as f:
data = json.load(f) # load() reads from a file, loads() reads from a string
# write a JSON file
with open("output.json", "w") as f:
json.dump(data, f, indent=2) # dump() writes to a file, dumps() returns a string
import requests # pip install requests
response = requests.get("https://api.example.com/users/42")
response.raise_for_status() # raises an error for 4xx/5xx responses
user = response.json() # parses the JSON body automatically
print(user["name"])
JSON Schema is a standard that lets you describe the expected shape of a JSON document: which fields are required, what type each field must be, and what values are allowed. It is used in API documentation (OpenAPI/Swagger), form validation, CI pipelines, and anywhere you need to verify that incoming JSON matches a contract.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["name", "age", "email"],
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
},
"email": {
"type": "string",
"format": "email"
},
"roles": {
"type": "array",
"items": { "type": "string" }
}
}
}
This schema requires name, age, and email. It allows an optional roles array. Any JSON that violates these rules — like a missing email field or an age of "twenty-five" — will fail validation.
type — the data type: "string", "number", "integer", "boolean", "array", "object", "null"required — array of property names that must be present in an objectproperties — defines the schema for each named property in an objectminLength / maxLength — minimum and maximum character length for stringsminimum / maximum — numeric range constraintsenum — value must be one of a fixed list: "enum": ["active", "inactive", "pending"]items — schema applied to each element inside an arrayformat — semantic hint like "email", "date", "uri" (validators may or may not enforce these)Well-structured JSON is easier to consume, easier to version, and less likely to break clients when things change. These practices are widely followed in production APIs.
Pick one naming convention for keys and stick to it across your entire API. camelCase is the most common choice for JSON APIs used by JavaScript clients. snake_case is common in Python and Ruby APIs.
// camelCase (recommended for JS/TS clients)
{ "userId": 42, "firstName": "Priya", "createdAt": "2025-01-15" }
// snake_case (common in Python APIs)
{ "user_id": 42, "first_name": "Priya", "created_at": "2025-01-15" }
// avoid mixing styles in the same API
{ "userId": 42, "first_name": "Priya" } // inconsistent — don't do this
Never return a bare array at the top level. Wrap it in an object so you can add metadata (pagination, status, errors) later without a breaking change.
// bad — a bare array is hard to extend
[{ "id": 1, "name": "Priya" }, { "id": 2, "name": "Rahul" }]
// good — an object wrapper leaves room to grow
{
"data": [
{ "id": 1, "name": "Priya" },
{ "id": 2, "name": "Rahul" }
],
"total": 2,
"page": 1
}
JSON has no native date type. Store dates as ISO 8601 strings. This format is unambiguous, sortable, and parseable in every language.
// bad — ambiguous, locale-dependent
{ "createdAt": "01/15/2025", "time": "3:30 PM IST" }
// good — ISO 8601, universally understood
{ "createdAt": "2025-01-15T09:30:00Z" }
When an API call fails, the error response should be predictable JSON — not plain text, not an HTML error page. Clients can then handle errors programmatically.
{
"error": {
"code": "VALIDATION_ERROR",
"message": "The 'email' field is required.",
"field": "email"
}
}
null and omit-key interchangeablyMissing key means "this field does not apply to this resource." null value means "this field applies but has no value yet." Mixing the two makes clients write extra defensive code to handle both cases.
// user has no middle name — field is optional, so omit it
{ "firstName": "Priya", "lastName": "Sharma" }
// user has a middle name field but hasn't set it yet — use null
{ "firstName": "Priya", "middleName": null, "lastName": "Sharma" }
Once you know JSON, you will start seeing it everywhere. Here are the most common places you will encounter it:
JSON.parse() or fetch's response.json().package.json defines a Node.js project's name, version, and dependencies. tsconfig.json configures TypeScript. .eslintrc.json configures linting rules. All are JSON files.JSON.stringify() before saving and JSON.parse() after retrieving is the standard pattern.turbo.json, Vercel config) are also JSON files.JSON is not the only way to represent structured data. Here is how it compares to the other formats you are likely to encounter:
XML was the dominant data format before JSON. JSON replaced it in most APIs because it is more compact, easier to read, and directly usable in JavaScript. XML still appears in SOAP APIs, RSS feeds, SVG files, and Android layouts. See the full comparison in JSON vs XML.
/* Same data in XML */
<user>
<name>Priya</name>
<age>25</age>
</user>
/* Same data in JSON */
{ "name": "Priya", "age": 25 }
YAML is popular for config files (Kubernetes, Docker Compose, GitHub Actions) because it supports comments and is easier to write by hand. However, YAML's indentation-sensitive syntax makes it prone to hard-to-spot errors. JSON is safer for data that machines generate and consume. Every valid JSON file is also valid YAML.
# Same data in YAML
name: Priya
age: 25
roles:
- admin
- editor
// Same data in JSON
{ "name": "Priya", "age": 25, "roles": ["admin", "editor"] }
CSV (comma-separated values) works well for flat, tabular data like spreadsheets or database exports. It has no support for nested structures. JSON handles nested and hierarchical data naturally, which is why APIs use JSON instead of CSV. When data is deeply nested (like an order with multiple line items, each with its own details), JSON is the only practical choice.
If you are new to JSON, these are the errors you are most likely to make. Each one will cause a parse error:
{ "a": 1, "b": 2, } — remove the comma after the last value.{ 'name': 'Priya' } — change all single quotes to double quotes.{ name: "Priya" } — add double quotes around the key: "name".{ "a": 1 // comment } — delete the comment entirely.{ "value": undefined } — JSON has no undefined. Use null or remove the key.{ "a": 1 "b": 2 } — add a comma after 1.{ "items": [1, 2, 3 } — the array is closed with } but should be ].Paste any broken JSON into the formatter and it will highlight the exact line and character that caused the error.