Learn JSON

Guides for formatting, validating, fixing, and understanding JSON.

JSON Learning Center

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.

New to JSON? Start here

These four guides take you from zero to confidently working with JSON in APIs and code:

  1. What Is JSON? — syntax, data types, objects, arrays, and where JSON appears in the real world.
  2. How to Format JSON — pretty-printing, minification, indentation, and when each format is appropriate.
  3. Common JSON Errors — the mistakes that appear most often and exactly how to fix them.
  4. Format API Response JSON — applying everything to real-world REST API output.

Already comfortable with JSON?

Skip ahead to the guides that match where you are:

Beginner guide

What Is JSON?

Learn JSON syntax, data types, nested objects, arrays, and the real-world places JSON appears.

Read guide →
Debugging reference

Common JSON Errors

Fix trailing commas, missing quotes, invalid escapes, mismatched brackets, and other frequent parse errors.

Read guide →
Error fixing

Fix Invalid JSON

Learn how to repair trailing commas, single quotes, unquoted keys, comments, and other invalid JSON syntax problems.

Read guide →
AI workflow

Fix AI-Generated JSON

Clean and validate JSON copied from ChatGPT, Claude, Cursor, Codex, and other AI tools without claiming the formatter is AI-powered.

Read guide →
Format comparison

JSON vs XML

Compare JSON and XML syntax, use cases, readability, ecosystem support, and API design tradeoffs.

Read guide →
FAQ

JSON FAQ

Answers to common questions about JSON syntax, validation, formatting, privacy, export, and loading data.

Read FAQ →

What JSON looks like

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.

Quick answers to common JSON questions

What is JSON used for?

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.

Is JSON the same as a JavaScript object?

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.

Why is my JSON invalid?

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.

Does JSON support comments?

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.

What is the difference between pretty-printed and minified JSON?

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.

Who these guides are for

  • Frontend and backend developers working with REST APIs, GraphQL, or any JSON-based data source
  • QA engineers and testers inspecting API responses and comparing payloads between environments
  • Data analysts processing JSON exports from databases, analytics platforms, or third-party tools
  • Students and beginners learning web development and encountering JSON for the first time
  • DevOps and platform engineers working with JSON-based config files, infrastructure-as-code, and structured log output

The six JSON data types

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.

1. String

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!"

2. Number

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

3. Boolean

Exactly two possible values: true or false. Both must be lowercase — True or FALSE will cause a parse error.

"isActive": true
"isDeleted": false

4. Null

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

5. Object

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"
}

6. Array

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 syntax rules

JSON has a strict set of rules. Even one small mistake makes the entire document invalid. These are the rules you must follow:

  • Keys must be double-quoted strings. { name: "Priya" } is invalid. { "name": "Priya" } is correct.
  • No trailing commas. The last item in an object or array must not have a comma after it. { "a": 1, } is invalid.
  • No comments. // this is a comment and /* block comment */ are both illegal inside JSON.
  • Strings must use double quotes. Single-quoted strings like 'hello' are not valid JSON.
  • Numbers must not be quoted. "age": "28" makes age a string, not a number.
  • Booleans and null are lowercase. True, False, NULL are all invalid.
  • All brackets and braces must be closed. Every { 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
}

How to read and write JSON in JavaScript

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.

JSON.parse() — convert a JSON string into an object

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"

JSON.stringify() — convert an object into a JSON string

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"
//   ]
// }

Accessing nested JSON values

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

Fetching JSON from an API in the browser

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.

Basic GET request

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);
  });

Using async/await (the modern pattern)

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);

Sending JSON in a POST request

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

Working with JSON in Python

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.

Parsing JSON (loads)

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

Serializing to JSON (dumps)

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"
#   ]
# }

Reading and writing JSON files in Python

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

Fetching JSON from an API in Python

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 — validating the structure of JSON

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.

A simple JSON Schema example

{
  "$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.

Key JSON Schema keywords

  • type — the data type: "string", "number", "integer", "boolean", "array", "object", "null"
  • required — array of property names that must be present in an object
  • properties — defines the schema for each named property in an object
  • minLength / maxLength — minimum and maximum character length for strings
  • minimum / maximum — numeric range constraints
  • enum — value must be one of a fixed list: "enum": ["active", "inactive", "pending"]
  • items — schema applied to each element inside an array
  • format — semantic hint like "email", "date", "uri" (validators may or may not enforce these)

JSON best practices for APIs

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.

Use consistent key naming

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

Always wrap API responses in a root object

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
}

Use ISO 8601 for dates and times

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" }

Return consistent error shapes

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"
  }
}

Do not use null and omit-key interchangeably

Missing 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" }

Where JSON appears in real projects

Once you know JSON, you will start seeing it everywhere. Here are the most common places you will encounter it:

  • REST API responses — any request to a web API (GitHub, Stripe, Twitter, Google Maps, weather APIs) returns a JSON body. You parse it with JSON.parse() or fetch's response.json().
  • Configuration filespackage.json defines a Node.js project's name, version, and dependencies. tsconfig.json configures TypeScript. .eslintrc.json configures linting rules. All are JSON files.
  • Browser localStorage and sessionStorage — browsers only store strings, so JSON.stringify() before saving and JSON.parse() after retrieving is the standard pattern.
  • NoSQL databases — MongoDB stores documents as BSON (a binary form of JSON). Firebase Firestore, DynamoDB, and CouchDB all use JSON-like document structures.
  • Log files — structured logging tools (like Winston, Pino, or Logstash) write log entries as JSON objects so they can be queried and filtered programmatically.
  • Data exchange between microservices — when one service calls another inside a backend system, the request and response bodies are almost always JSON.
  • GitHub and CI/CD pipelines — GitHub Actions workflow files are YAML, but the GitHub API and webhooks return JSON. Many build tools (like turbo.json, Vercel config) are also JSON files.

JSON vs other data formats

JSON is not the only way to represent structured data. Here is how it compares to the other formats you are likely to encounter:

JSON vs XML

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 }

JSON vs YAML

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"] }

JSON vs CSV

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.

The most common JSON mistakes and how to fix them

If you are new to JSON, these are the errors you are most likely to make. Each one will cause a parse error:

  • Trailing comma{ "a": 1, "b": 2, } — remove the comma after the last value.
  • Single quotes{ 'name': 'Priya' } — change all single quotes to double quotes.
  • Unquoted key{ name: "Priya" } — add double quotes around the key: "name".
  • Comment inside JSON{ "a": 1 // comment } — delete the comment entirely.
  • Undefined value{ "value": undefined } — JSON has no undefined. Use null or remove the key.
  • Missing comma between items{ "a": 1 "b": 2 } — add a comma after 1.
  • Mismatched brackets{ "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.