On this page
JSON
JSON (JavaScript Object Notation) is a lightweight text format for structured data. It is the standard format for APIs and configuration files.
JSON Syntax Rules
- Keys must be double-quoted strings
- Values: string, number, boolean, null, array, object
- No functions,
undefined, comments, or trailing commas
{
"name": "Alice",
"age": 25,
"active": true,
"tags": ["js", "web"],
"address": {
"city": "New York"
}
}
JSON.stringify
Convert JavaScript values to JSON string:
let user = {
name: 'Bob',
age: 30,
greet() { return 'hi'; } // functions omitted
};
JSON.stringify(user);
// '{"name":"Bob","age":30}'
// Pretty print
JSON.stringify(user, null, 2);
// Replacer function
JSON.stringify(user, ['name']); // '{"name":"Bob"}'
Handling undefined and special values
JSON.stringify({ a: 1, b: undefined }); // '{"a":1}' — b omitted
JSON.stringify({ a: NaN, b: Infinity }); // '{"a":null,"b":null}'
JSON.parse
Convert JSON string back to JavaScript:
let json = '{"name":"Charlie","age":28}';
let obj = JSON.parse(json);
console.log(obj.name); // 'Charlie'
Reviver function
let data = JSON.parse('{"date":"2024-06-13"}', (key, value) => {
if (key === 'date') return new Date(value);
return value;
});
Working with APIs
async function fetchUser(id) {
const response = await fetch(`https://api.example.com/users/${id}`);
const user = await response.json(); // parse JSON automatically
return user;
}
async function createUser(userData) {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(userData)
});
return response.json();
}
Deep Clone (Simple Objects)
let original = { a: 1, b: { c: 2 } };
let copy = JSON.parse(JSON.stringify(original));
copy.b.c = 99;
console.log(original.b.c); // 2 — deep copy
// Limitation: loses Date, Map, Set, functions, undefined
Common Errors
// Invalid JSON
JSON.parse("{ name: 'Alice' }"); // SyntaxError — keys must be quoted
// Circular reference
let obj = {};
obj.self = obj;
JSON.stringify(obj); // TypeError: Converting circular structure to JSON
JSON is essential for web development — nearly every REST API uses it for request and response bodies.