What is JSON? A Complete Developer's Guide
Introduction
JSON (JavaScript Object Notation) is the de-facto standard for data exchange on the modern web. If you have ever called a REST API, parsed a configuration file, or worked with a NoSQL database, you have worked with JSON. Understanding it thoroughly — not just the basics — is an essential skill for every developer.
This guide covers everything: what JSON is, its full syntax, all six data types, the difference between JSON and JavaScript objects, common real-world mistakes, and how to validate and format JSON when something goes wrong.
What is JSON?
JSON is a lightweight, text-based format for representing structured data. It was originally derived from JavaScript object literal syntax, but today it is completely language-independent. The format is defined by RFC 8259 and is natively supported in virtually every programming language.
JSON is used to:
- Transfer data between a client and a server (REST APIs return JSON responses)
- Store structured configuration (package.json, tsconfig.json, .eslintrc)
- Persist documents in NoSQL databases (MongoDB, CouchDB, Firestore)
- Serialize application state for caching or logging
JSON Syntax: The Rules
JSON has a strict syntax. Unlike JavaScript, there is no flexibility here — every character matters.
1. A JSON document is either an object or an array at the root level
{ "name": "Alice" }
or
["apple", "banana", "cherry"]
2. Objects use curly braces {}
An object is a collection of key-value pairs.
{
"id": 1,
"name": "Alice Johnson",
"email": "alice@example.com",
"isActive": true
}
3. Arrays use square brackets []
An array is an ordered list of values.
["JavaScript", "TypeScript", "Python"]
4. Keys must always be strings in double quotes
This is the most common mistake coming from JavaScript, where you can write { name: "Alice" }. In JSON, the key must be quoted:
{ "name": "Alice" } ✅ Valid
{ name: "Alice" } ❌ Invalid — key must be quoted
{ 'name': 'Alice' } ❌ Invalid — single quotes not allowed
5. Strings must use double quotes
{ "city": "Kuala Lumpur" } ✅ Valid
{ "city": 'Kuala Lumpur' } ❌ Invalid — single quotes not allowed
JSON Data Types
JSON supports exactly six data types. Nothing else.
1. String
A sequence of Unicode characters enclosed in double quotes.
{ "username": "dev_shahzaib" }
Special characters inside strings must be escaped with a backslash:
| Character | Escaped form |
|---|---|
" | \" |
\ | \\ |
| newline | \n |
| tab | \t |
| carriage return | \r |
2. Number
Integers or floating-point values. No quotes, no NaN, no Infinity.
{ "age": 30, "score": 98.5, "temperature": -12 }
3. Boolean
The literals true or false — lowercase only.
{ "isLoggedIn": true, "hasError": false }
4. Null
The literal null — lowercase only. Represents an intentionally empty value.
{ "middleName": null }
5. Object
A nested collection of key-value pairs.
{
"user": {
"id": 42,
"name": "Bob"
}
}
6. Array
An ordered list of any of the above types (they can be mixed).
{
"tags": ["api", "rest", "json"],
"scores": [98, 85, 72],
"mixed": [1, "hello", true, null]
}
A Complete JSON Example
Here is a realistic JSON response you might receive from a REST API:
{
"status": "success",
"data": {
"user": {
"id": 1042,
"name": "Alice Johnson",
"email": "alice@example.com",
"role": "admin",
"isActive": true,
"lastLogin": "2026-09-15T08:30:00Z",
"preferences": {
"theme": "dark",
"language": "en"
},
"permissions": ["read", "write", "delete"]
}
},
"timestamp": 1726387800,
"errors": null
}
This example demonstrates nesting, arrays, all primitive types, and null.
JSON vs JavaScript Objects
JSON and JavaScript object literal syntax look almost identical, but they are not the same thing.
| Feature | JSON | JavaScript Object |
|---|---|---|
| Keys | Must be double-quoted strings | Can be unquoted identifiers |
| String values | Double quotes only | Single or double quotes |
| Trailing commas | Not allowed | Allowed in modern JS |
| Functions | Not allowed | Allowed |
undefined | Not allowed | Allowed |
NaN, Infinity | Not allowed | Allowed |
| Comments | Not allowed | Not allowed (but supported in some config parsers) |
Converting between them in JavaScript
// JavaScript object → JSON string
const user = { id: 1, name: "Alice", active: true };
const jsonString = JSON.stringify(user);
// → '{"id":1,"name":"Alice","active":true}'
// JSON string → JavaScript object
const parsed = JSON.parse(jsonString);
console.log(parsed.name); // → "Alice"
// Pretty-printed JSON (useful for logging)
console.log(JSON.stringify(user, null, 2));
Common JSON Errors and How to Fix Them
The JSON specification is strict. Here are the errors developers encounter most often:
Error 1: Single quotes instead of double quotes
// ❌ Invalid
{ 'name': 'Alice' }
// ✅ Fixed
{ "name": "Alice" }
Error 2: Trailing comma after the last item
This is legal in modern JavaScript but not in JSON.
// ❌ Invalid — trailing comma
{
"name": "Alice",
"role": "admin",
}
// ✅ Fixed — remove the trailing comma
{
"name": "Alice",
"role": "admin"
}
Error 3: Unquoted keys
// ❌ Invalid
{ name: "Alice" }
// ✅ Fixed
{ "name": "Alice" }
Error 4: Using JavaScript-only values
// ❌ Invalid — undefined and NaN are not valid JSON
{ "value": undefined, "score": NaN }
// ✅ Fixed — use null for missing values
{ "value": null, "score": null }
Error 5: Unescaped special characters in strings
// ❌ Invalid — raw newline inside string
{ "message": "Hello
World" }
// ✅ Fixed — use escape sequence
{ "message": "Hello\nWorld" }
For a complete reference on all JSON error types and how to resolve each one, see the full guide on how to fix invalid JSON.
Pretty-Print vs Minified JSON
JSON can be formatted in two ways:
Pretty-printed — easier to read, larger in size:
{
"id": 1,
"name": "Alice",
"active": true
}
Minified — compact, used in API responses and production:
{"id":1,"name":"Alice","active":true}
In JavaScript, JSON.stringify(data, null, 2) produces pretty-printed output. JSON.stringify(data) produces minified output.
Use our free JSON Formatter to instantly switch between the two, or the JSON Validator to check whether a JSON string is syntactically correct. If you need rows and columns, convert JSON data into CSV in your browser.
JSON in Real Projects
Reading a package.json
Every Node.js project has a package.json at its root. This is a JSON file that describes the project, its dependencies, and its scripts:
{
"name": "my-project",
"version": "1.0.0",
"scripts": {
"dev": "next dev",
"build": "next build"
},
"dependencies": {
"react": "^18.0.0",
"next": "^14.0.0"
}
}
Parsing a REST API Response
async function fetchUser(id) {
const response = await fetch(`/api/users/${id}`);
const data = await response.json(); // Automatically parses JSON
return data.user.name;
}
Storing Data in localStorage
// Save
localStorage.setItem("settings", JSON.stringify({ theme: "dark", lang: "en" }));
// Retrieve
const settings = JSON.parse(localStorage.getItem("settings"));
console.log(settings.theme); // → "dark"
Related Tools and Guides
If you are working with JSON on a daily basis, these tools will save you time:
- JSON Formatter — Format, beautify, or minify any JSON string instantly in your browser
- JSON Validator — Validate JSON and see the exact location of syntax errors
- JSON to CSV Converter — Convert JSON data into CSV or turn CSV rows back into JSON in your browser
- JSON vs XML — In-depth comparison of when to use JSON versus XML
- What Is JWT? — Learn how JSON Web Tokens use compact JSON objects for authentication and API authorization
Summary
- JSON is a text-based, language-independent format for structured data
- It supports exactly six types: string, number, boolean, null, object, and array
- Keys must be double-quoted strings; single quotes are not valid JSON
- Trailing commas are not allowed
- Values like
undefined,NaN, andInfinityare not valid JSON - Use
JSON.parse()to convert a JSON string to a JavaScript object, andJSON.stringify()to do the reverse - Always validate your JSON when debugging — use the free JSON Validator to find exact error locations