JSON (JavaScript Object Notation) is a lightweight, text-based format for storing and exchanging data. Despite having "JavaScript" in its name, JSON is completely language-independent and is supported natively by virtually every modern programming language - from Python and Java to Ruby, Go, and PHP.

If you have ever used a web application, consumed a REST API, or worked with configuration files, you have almost certainly worked with JSON - even if you did not realise it. It is the backbone of modern data exchange on the internet.

A Brief History of JSON

JSON was created by Douglas Crockford in the early 2000s as a simpler alternative to XML for exchanging data between a server and a web browser. Crockford noticed that JavaScript already had a built-in way to represent data structures using object and array literals, and he formalised this into a specification.

The first JSON website went live in 2002, and the format was standardised as ECMA-404 in 2013 and RFC 8259 in 2017. Before JSON became dominant, XML was the primary format for APIs - but JSON's simplicity and smaller payload size made it rapidly replace XML in most web applications throughout the 2000s and 2010s.

The Basic Structure of JSON

A JSON document is built from two fundamental structures:

  • Objects - An unordered collection of key-value pairs, enclosed in curly braces {}. Each key must be a string in double quotes, followed by a colon and the value.
  • Arrays - An ordered list of values, enclosed in square brackets []. Values are separated by commas.

Here is a real-world example of a JSON object representing a user profile:

{
  "id": 1042,
  "name": "Alice Johnson",
  "email": "alice@example.com",
  "age": 30,
  "isActive": true,
  "balance": 1250.75,
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "state": "NY",
    "zip": "10001",
    "country": "USA"
  },
  "tags": ["developer", "designer", "admin"],
  "lastLogin": "2024-01-14T09:30:00Z",
  "preferences": null
}

JSON Data Types

JSON supports exactly six data types. Understanding these is essential because JSON is strictly typed - unlike JavaScript itself, which allows many implicit type conversions.

1. String

Text enclosed in double quotes. Single quotes are NOT valid in JSON. Strings support Unicode and can contain escape sequences like \n (newline), \t (tab), and \" (escaped quote).

"name": "Alice Johnson"
"emoji": "Hello ❤"
"multiline": "Line one\nLine two"

2. Number

Integer or floating-point numbers. JSON does not distinguish between integers and decimals - both are just "numbers". There is no separate type for BigInt, complex numbers, or special values like Infinity or NaN.

"age": 30
"price": 19.99
"temperature": -5.2
"distance": 1.5e10

3. Boolean

Either true or false - lowercase only. Unlike JavaScript, JSON does not accept True, False, 1, or 0 as booleans.

"isActive": true
"isDeleted": false

4. Null

Represents the intentional absence of a value. Use null when a field exists in the schema but has no value - this is different from omitting the field entirely.

"middleName": null
"deletedAt": null

5. Object

A nested set of key-value pairs enclosed in curly braces. Objects can be nested to any depth, creating hierarchical data structures.

"address": {
  "city": "New York",
  "zip": "10001"
}

6. Array

An ordered list of values enclosed in square brackets. Arrays can contain any mix of JSON types - including other objects and arrays.

"scores": [95, 87, 92, 100]
"items": [{"id": 1}, {"id": 2}]
"mixed": [1, "hello", true, null]

JSON Syntax Rules

JSON has a small but strict set of syntax rules that trip up many beginners:

  • Keys must be strings in double quotes - {"name": "Alice"} is valid, {name: "Alice"} is not
  • Double quotes only - single quotes are not valid anywhere in JSON
  • No trailing commas - {"a": 1, "b": 2,} is invalid JSON
  • No comments - JSON does not support // comments or /* block comments */
  • No undefined - JavaScript's undefined has no equivalent in JSON
  • No functions - functions cannot be stored in JSON

Parsing and Stringifying JSON

Working with JSON in code means converting between JSON strings and native data structures. This is called parsing (string to object) and stringifying (object to string).

In JavaScript:

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

// Stringify a JavaScript object into a JSON string
const user = { name: "Bob", age: 25 };
const str = JSON.stringify(user);
console.log(str); // '{"name":"Bob","age":25}'

// Pretty-print with indentation
const pretty = JSON.stringify(user, null, 2);
console.log(pretty);
// {
//   "name": "Bob",
//   "age": 25
// }

In Python:

import json

# Parse JSON string
json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)
print(data["name"])  # Alice

# Convert Python dict to JSON string
user = {"name": "Bob", "age": 25}
json_str = json.dumps(user)
print(json_str)  # {"name": "Bob", "age": 25}

# Pretty-print
pretty = json.dumps(user, indent=2)

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

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

JSON vs XML: Why JSON Won

Before JSON, XML was the dominant data exchange format for web services (SOAP APIs used XML extensively). JSON replaced it in most use cases because of several key advantages:

  • Less verbose - the same data takes significantly fewer characters in JSON than XML
  • Easier to read - the syntax is closer to how programmers already think about data
  • Native JavaScript support - browsers can parse JSON directly without additional libraries
  • Smaller payloads - less data transferred means faster API responses
  • Simpler to parse - most languages have JSON support built in

Here is the same data in both formats to illustrate the difference:

// JSON (56 characters)
{"user": {"name": "Alice", "age": 30}}

// XML (equivalent, 67+ characters)
<user><name>Alice</name><age>30</age></user>

Where JSON is Used

JSON appears throughout modern software development in many different contexts:

  • REST APIs - the universal format for request bodies and response payloads
  • Configuration files - package.json in Node.js, tsconfig.json in TypeScript, settings.json in VS Code
  • NoSQL databases - MongoDB stores documents as BSON (Binary JSON), Firebase uses JSON natively, PostgreSQL has JSONB column type
  • Browser storage - localStorage and sessionStorage store data as JSON strings
  • Structured logging - tools like Logstash and Splunk ingest JSON logs
  • Data serialisation - sending objects between microservices
  • GraphQL - all GraphQL responses are JSON
  • Webhook payloads - event-driven systems send JSON payloads to subscribed endpoints

Common JSON Mistakes to Avoid

Even experienced developers make these errors when writing JSON manually:

  • Using single quotes instead of double quotes for strings or keys
  • Leaving a trailing comma after the last item in an object or array
  • Trying to add comments to a JSON file
  • Using undefined as a value (it gets stripped by JSON.stringify)
  • Storing dates as Date objects instead of ISO 8601 strings like "2024-01-15T09:30:00Z"

Validating JSON

When a JSON string fails to parse, it usually means there is a syntax error. You can validate JSON quickly using:

  • Browser console - paste JSON.parse('your json here') and check for errors
  • Online validators - many free tools will highlight exactly where your JSON is malformed
  • Code editors - VS Code highlights JSON errors in .json files automatically

Explore Your JSON Structure Instantly

Once your JSON is valid, use JSON Keyper to extract every key path - including nested objects and arrays - in one click. Free, no login required.

Open JSON Keyper