JSON Guide

What Is JSON? A Complete Guide to JavaScript Object Notation

By S. Nitya·Published ·Updated ·12 min read

JSON — JavaScript Object Notation — is the universal language of data on the web. From the API powering your favourite app to the configuration file in your code editor, JSON is everywhere. This guide covers everything you need to know: syntax, data types, parsing, REST APIs, and best practices, with concrete examples throughout.

What Is JSON?

JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format. It represents structured data as human-readable text, making it easy for both people and programs to read and write. A JSON document is simply a string of characters that encodes a value — most often an object or an array.

Here is a minimal JSON example — a user record:

{
  "id": "usr_001",
  "name": "Alice Smith",
  "age": 30,
  "active": true,
  "roles": ["admin", "editor"],
  "address": {
    "city": "London",
    "country": "GB"
  }
}

JSON is defined by two structures: objects (key-value pairs enclosed in curly braces) and arrays (ordered lists enclosed in square brackets). These two structures can be nested inside each other to any depth, making JSON flexible enough to represent virtually any data shape.

Although its name references JavaScript, JSON is language-independent. Parsers and generators exist for every major programming language, and JSON is defined by its own formal specification — not by JavaScript itself.

A Brief History of JSON

JSON was created by Douglas Crockford around 2001 while he was working on State Software, building AJAX-based web applications before “AJAX” was even a coined term. Crockford needed a simple way to pass data between a web server and a browser without a page reload, and he noticed that JavaScript's built-in object literal syntax was already a perfectly good data format.

The first JSON.org website was registered in 2002. The format spread quickly because it required no special parser in the browser — early implementations simply used JavaScript's eval() function, though this was later replaced with dedicated parsers for security reasons.

Key milestones in JSON's standardisation:

  • 2006 — RFC 4627 published, the first formal specification of JSON.
  • 2013 — ECMA-404 (the JSON Data Interchange Standard) released by ECMA International.
  • 2017 — RFC 8259 obsoleted earlier RFCs and became the definitive IETF standard, mandating UTF-8 encoding.
  • Today — JSON is the de-facto standard for web APIs, configuration files, log formats, and data serialisation across every major programming ecosystem.

Crockford famously said he did not invent JSON — he discovered it. The format had been lurking in JavaScript all along; he simply gave it a name and a spec.

JSON Syntax Rules

JSON has just five syntax rules. Violating any one of them produces an invalid document that parsers will reject with an error.

  1. Data is in name/value pairs. Every key must be a string in double quotes, followed by a colon, followed by a value: "name": "Alice"
  2. Data is separated by commas. Pairs within an object and items within an array are separated by commas — but no trailing comma is allowed after the last item.
  3. Objects use curly braces. An object is a set of name/value pairs wrapped in {}.
  4. Arrays use square brackets. An array is an ordered collection of values wrapped in [].
  5. No comments allowed. JSON has no syntax for comments. If you need to annotate config files, use a superset like JSON5 or JSONC, or move notes to a separate documentation key.

Valid vs Invalid JSON

✓ Valid

{
  "name": "Alice",
  "age": 30,
  "active": true
}

✗ Invalid (trailing comma + single quotes)

{
  'name': 'Alice',
  'age': 30,
  'active': true,
}

Validate your JSON instantly

Paste any JSON into the free JSON Formatter — it highlights syntax errors, beautifies, and minifies, entirely in your browser.

Open JSON Formatter

JSON Data Types

JSON supports exactly six value types. Understanding each one prevents type-mismatch bugs when exchanging data between systems.

1. String

A sequence of Unicode characters enclosed in double quotes. Single quotes are not valid. Use backslash escape sequences for special characters.

"name": "Alice Smith"
"greeting": "Hello, \u4e16\u754c"
"path": "C:\\Users\\Alice"

2. Number

An integer or floating-point number. JSON does not distinguish between the two. Special values like NaN and Infinity are not valid JSON numbers.

"age": 30
"price": 9.99
"scientific": 1.5e3

3. Boolean

Either true or false — lowercase only. True and False are not valid.

"active": true
"verified": false

4. Null

Represents the intentional absence of a value. Written as null (lowercase only).

"deletedAt": null

5. Array

An ordered list of values enclosed in square brackets. Values can be any JSON type and can be mixed.

"roles": ["admin", "editor", "viewer"]
"scores": [98, 87, 95]
"mixed": [1, "two", true, null]

6. Object

An unordered collection of name/value pairs in curly braces. Keys must be unique strings; values can be any JSON type.

"address": {
  "street": "10 Downing St",
  "city": "London",
  "postcode": "SW1A 2AA"
}

JSON vs XML

Before JSON, XML was the dominant format for data exchange on the web. Both formats are human-readable and widely supported, but they differ significantly in verbosity, tooling, and use cases.

FeatureJSONXML
VerbosityCompact — less boilerplateVerbose — opening and closing tags
ReadabilityCleaner for simple dataBetter for document-like data
CommentsNot supportedSupported (<!-- -->)
Data types6 native typesEverything is a string by default
Parsing speedGenerally fasterSlower due to complexity
Browser supportNative via JSON.parseRequires DOMParser or XSLT
Schema validationJSON SchemaDTD, XSD, RelaxNG
AttributesNo concept of attributesSupports element attributes
NamespacesNot supportedFull namespace support
Best forWeb APIs, config files, logsDocuments, SOAP, XSLT pipelines

Same data, two formats

JSON — compact

{
  "name": "Alice",
  "age": 30
}

XML — verbose

<user>
  <name>Alice</name>
  <age>30</age>
</user>

Bottom line: Use JSON for modern web APIs and application data. Reach for XML when you need document structure, XSLT transformations, namespaces, or when integrating with legacy enterprise systems (SOAP, EDI).

Convert JSON to XML (or XML to JSON)

Need to bridge the two formats? The free JSON ↔ XML Converter handles it instantly, in your browser.

Open JSON ↔ XML Converter

Parsing and Creating JSON

Every major programming language ships with a JSON library. Here are the most common patterns.

JavaScript

JavaScript has two built-in methods: JSON.parse() converts a JSON string into a JavaScript object, and JSON.stringify() serialises a JavaScript value to a JSON string.

// Parse JSON string → JavaScript object
const jsonString = '{"name":"Alice","age":30}';
const user = JSON.parse(jsonString);
console.log(user.name); // "Alice"

// Stringify JavaScript object → JSON string
const obj = { name: "Bob", active: true };
const json = JSON.stringify(obj, null, 2);
// {
//   "name": "Bob",
//   "active": true
// }

// Fetch JSON from an API
const response = await fetch('https://api.example.com/users/1');
const data = await response.json(); // automatically parsed

Python

Python's standard library includes the json module. Use json.loads() to parse a string and json.dumps() to serialise. For reading and writing files, use json.load() and json.dump().

import json

# Parse JSON string → Python dict
json_str = '{"name": "Alice", "age": 30}'
user = json.loads(json_str)
print(user["name"])  # Alice

# Serialise Python dict → JSON string
data = {"name": "Bob", "active": True}
output = json.dumps(data, indent=2)
# {
#   "name": "Bob",
#   "active": true
# }

# Read from file
with open("data.json") as f:
    config = json.load(f)

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

Other Languages — Quick Reference

LanguageParse (JSON → object)Serialize (object → JSON)
JavaObjectMapper.readValue()ObjectMapper.writeValueAsString()
Gojson.Unmarshal()json.Marshal()
PHPjson_decode()json_encode()
RubyJSON.parse()object.to_json
C#JsonSerializer.Deserialize()JsonSerializer.Serialize()
Rustserde_json::from_str()serde_json::to_string()

Convert JSON to YAML, XML, or text

Need JSON as YAML, XML, or plain text? Use the free converters — all processing happens instantly in your browser.

Convert JSON to YAML

JSON in REST APIs

JSON is the default data format for virtually every modern REST API. When a client sends or requests data, it signals the format using HTTP headers.

  • Content-Type: application/json — tells the server the request body is JSON.
  • Accept: application/json — tells the server the client wants a JSON response.

A typical REST API interaction:

// POST request with a JSON body
POST /api/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Accept: application/json

{
  "name": "Alice Smith",
  "email": "alice@example.com",
  "role": "editor"
}

// 201 Created response
HTTP/1.1 201 Created
Content-Type: application/json

{
  "id": "usr_abc123",
  "name": "Alice Smith",
  "email": "alice@example.com",
  "role": "editor",
  "createdAt": "2026-05-23T10:00:00.000Z"
}

Standard HTTP status codes accompany JSON responses: 200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500 Internal Server Error. Error responses also return JSON, typically with an "error" or "message" key describing what went wrong.

JSON Schema

JSON Schema is a vocabulary for describing and validating the structure of JSON data. A schema is itself a JSON document that declares what types, formats, and constraints a valid JSON instance must satisfy.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["name", "email"],
  "properties": {
    "name":  { "type": "string", "minLength": 1 },
    "email": { "type": "string", "format": "email" },
    "age":   { "type": "integer", "minimum": 0 }
  },
  "additionalProperties": false
}

JSON Schema is widely used for API contract validation, IDE auto-completion (VS Code uses it for package.json and most config files), and automated form validation. The current specification is Draft 2020-12.

JSON Best Practices

  1. Use camelCase for key names. It aligns with JavaScript convention and is the most common style in REST APIs — for example, createdAt not created_at. Be consistent: pick one style and stick to it.
  2. Always use UTF-8 encoding. RFC 8259 mandates UTF-8 for JSON transmitted over networks. Declare Content-Type: application/json; charset=utf-8 in HTTP responses.
  3. Avoid deeply nested structures. Nesting beyond 3–4 levels makes JSON hard to consume. Flatten where possible or use ID references instead of embedding full sub-objects.
  4. Use ISO 8601 for dates and times. JSON has no native date type. Always serialise timestamps as strings in ISO 8601 format: "2026-05-23T10:00:00.000Z".
  5. Validate at system boundaries. Validate incoming JSON against a schema or typed model at every API endpoint or file-read point. Never trust raw input.

Common JSON Errors

These four mistakes account for the vast majority of JSON parse errors in the wild.

Error: Trailing comma

✗ Invalid

{ "name": "Alice", "age": 30, }

✓ Fixed

{ "name": "Alice", "age": 30 }
Remove the comma after the last item in every object and array.
Error: Single quotes instead of double quotes

✗ Invalid

{ 'name': 'Alice' }

✓ Fixed

{ "name": "Alice" }
JSON requires double quotes for all strings and keys, no exceptions.
Error: Unquoted key

✗ Invalid

{ name: "Alice" }

✓ Fixed

{ "name": "Alice" }
Unlike JavaScript object literals, JSON keys must always be quoted strings.
Error: NaN or Infinity as a number

✗ Invalid

{ "ratio": NaN, "limit": Infinity }

✓ Fixed

{ "ratio": null, "limit": 1e308 }
Use null or a very large finite number instead. NaN and Infinity are not valid JSON.

Frequently Asked Questions

What does JSON stand for?
JSON stands for JavaScript Object Notation. It is a lightweight, text-based data interchange format that is easy for humans to read and write, and easy for machines to parse and generate.
Is JSON the same as JavaScript?
No. JSON is inspired by JavaScript object literal syntax, but it is language-independent. Nearly every modern programming language — Python, Java, Go, Ruby, PHP, C#, and more — has built-in libraries to read and write JSON.
What are the 6 JSON data types?
JSON supports six value types: string (text in double quotes), number (integer or decimal), boolean (true or false), null, array (ordered list in square brackets), and object (key-value pairs in curly braces).
When should I use JSON instead of XML?
JSON is generally preferred for web APIs, JavaScript applications, and configuration files because it is lighter, easier to parse, and maps directly to native data structures in most languages. XML remains preferable for document-centric data, XSLT transformations, or schemas that require XML-specific features like namespaces.
How do I validate JSON online for free?
Use the free JSON Formatter at jsonbuddy.net/json-formatter. Paste your JSON and the tool instantly highlights syntax errors, validates the structure, and lets you beautify or minify the output — all in your browser without sending data to any server.

Ready to work with JSON?

JSON Buddy gives you 17 free browser-based tools — format, validate, convert, and diff JSON, YAML, and XML. No signup. Your data never leaves your browser.