JavaScript 26 🧬 JSON
JSON is a lightweight data interchange format — easy for humans to read and write, and easy for machines to parse and generate. It’s the standard for sending data between a client and a server.
A Quick Look at the Examples
// 1. Parsing JSON
const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // "John"
console.log(obj.age); // 30
console.log(obj.city); // "New York"
// 2. Parsing with a reviver function
const jsonString2 = '{"name": "John", "age": 30}';
const obj2 = JSON.parse(jsonString2, (key, value) => {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
});
console.log(obj2.name); // "JOHN"
console.log(obj2.age); // 30
// 3. Handling invalid JSON
try {
const jsonString = '{"name": "John", "age": 30, "city": "New York"'; // missing }
const obj = JSON.parse(jsonString);
} catch (error) {
console.error("Invalid JSON:", error.message);
}
// 4. Stringifying an object
const obj3 = { name: "John", age: 30, city: "New York" };
const jsonString3 = JSON.stringify(obj3);
console.log(jsonString3); // '{"name":"John","age":30,"city":"New York"}'
// 5. Pretty printing
const jsonString4 = JSON.stringify(obj3, null, 2);
console.log(jsonString4);
// {
// "name": "John",
// "age": 30,
// "city": "New York"
// }
// 6. Stringifying with a replacer function
const jsonString5 = JSON.stringify(obj3, (key, value) => {
if (typeof value === 'string') {
return value.toLowerCase();
}
return value;
});
console.log(jsonString5); // '{"name":"john","age":30,"city":"new york"}'
a. What is JSON?
JSON (JavaScript Object Notation) is a lightweight data interchange format. It’s easy for humans to read and write, and easy for machines to parse and generate.
JSON is Based on Two Structures
| Structure | Description |
|---|---|
| Objects | An unordered set of name/value pairs |
| Arrays | An ordered collection of values |
JSON Data Types
| Type | Example | Notes |
|---|---|---|
| Object | { "name": "John" } | Curly braces |
| Array | [1, 2, 3] | Square brackets |
| String | "hello" | Double quotes only |
| Number | 42, 3.14 | Integer or floating point |
| Boolean | true, false | Lowercase |
| Null | null | Lowercase |
⚠️ Important: In JSON, strings must use double quotes — single quotes are NOT valid JSON!
// ✅ Valid JSON
'{"name": "John", "age": 30}'
// ❌ Invalid JSON — single quotes not allowed
"{'name': 'John', 'age': 30}"
JSON vs JavaScript Objects
| Aspect | JSON | JavaScript Object |
|---|---|---|
| Keys | Must be in double quotes | Can be unquoted |
| Strings | Double quotes only | Single or double quotes |
| Comments | ❌ Not allowed | ✅ Allowed |
| Trailing commas | ❌ Not allowed | ✅ Allowed (ES5+) |
| Methods | ❌ Not allowed | ✅ Allowed |
undefined | ❌ Not allowed | ✅ Allowed |
// JavaScript object (valid JS, but NOT valid JSON)
const jsObj = {
name: 'John', // Single quotes OK in JS
greet() { }, // Methods OK in JS
age: 30, // Trailing commas OK
};
// JSON (strict format)
const json = '{"name": "John", "age": 30}';
Safety Notes
- Always handle errors when parsing JSON strings using
try-catchblocks - Avoid serializing large objects if performance is a concern
- Be cautious when parsing JSON from untrusted sources — avoid XSS and JSON hijacking
b. JSON with JavaScript
JavaScript provides two methods to work with JSON:
| Method | Description |
|---|---|
JSON.parse() | Converts JSON string → JavaScript object |
JSON.stringify() | Converts JavaScript object → JSON string |
JSON.parse()
Parses a JSON string and constructs the JavaScript value or object described by the string.
const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // "John"
Reviver Function
JSON.parse() accepts an optional second argument — a reviver function — called for each member of the object after parsing.
const jsonString = '{"name": "John", "age": 30}';
const obj = JSON.parse(jsonString, (key, value) => {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
});
console.log(obj.name); // "JOHN"
console.log(obj.age); // 30 (numbers unchanged)
How the reviver works:
- Called for every key-value pair (including nested)
- Receives
keyandvalue - Returns the transformed value
- If it returns
undefined, the property is removed
Example — convert date strings to Date objects:
const jsonString = '{"name": "Event", "date": "2024-01-15"}';
const obj = JSON.parse(jsonString, (key, value) => {
if (key === 'date') return new Date(value);
return value;
});
console.log(obj.date instanceof Date); // true
Error Handling with JSON.parse()
JSON.parse() throws a SyntaxError if the input is not valid JSON. Always handle errors with try-catch.
try {
const jsonString = '{"name": "John", "age": 30'; // Missing closing }
const obj = JSON.parse(jsonString);
} catch (error) {
console.error("Invalid JSON:", error.message);
// "Invalid JSON: Unexpected end of JSON input"
}
Common JSON errors:
| Error | Cause |
|---|---|
Unexpected token | Single quotes, missing quotes, trailing comma |
Unexpected end of JSON input | Incomplete JSON |
Unexpected number in JSON | Leading zeros, NaN, Infinity |
// Safe parse function
function safeParse(json, fallback = null) {
try {
return JSON.parse(json);
} catch (error) {
console.error("Parse failed:", error.message);
return fallback;
}
}
console.log(safeParse('{"a": 1}')); // { a: 1 }
console.log(safeParse('invalid', {})); // {} (fallback)
JSON.stringify()
Converts a JavaScript object or value to a JSON string.
const obj = { name: "John", age: 30, city: "New York" };
const jsonString = JSON.stringify(obj);
console.log(jsonString);
// '{"name":"John","age":30,"city":"New York"}'
What gets included:
| Value | Included? |
|---|---|
| String, number, boolean | ✅ Yes |
null | ✅ Yes |
undefined | ❌ No (omitted) |
| Function | ❌ No (omitted) |
| Symbol | ❌ No (omitted) |
| Date | ✅ Yes (as ISO string) |
const obj = {
name: "John", // ✅ Included
age: 30, // ✅ Included
isActive: true, // ✅ Included
address: null, // ✅ Included
greet: function() {}, // ❌ Omitted
nickname: undefined, // ❌ Omitted
id: Symbol('id'), // ❌ Omitted
created: new Date() // ✅ As ISO string
};
console.log(JSON.stringify(obj));
// '{"name":"John","age":30,"isActive":true,"address":null,"created":"2024-01-15T..."}'
Pretty Printing
Pass a third argument to JSON.stringify() to format the output.
| Value | Effect |
|---|---|
null | No indentation (default) |
2 | 2 spaces |
4 | 4 spaces |
"\t" | Tab character |
const obj = { name: "John", age: 30, city: "New York" };
// Compact (default)
console.log(JSON.stringify(obj));
// '{"name":"John","age":30,"city":"New York"}'
// Pretty with 2-space indent
console.log(JSON.stringify(obj, null, 2));
// {
// "name": "John",
// "age": 30,
// "city": "New York"
// }
// Pretty with 4-space indent
console.log(JSON.stringify(obj, null, 4));
Replacer Function
JSON.stringify() accepts a second argument — a replacer function — called for each member before stringification.
const obj = { name: "John", age: 30, city: "New York" };
const jsonString = JSON.stringify(obj, (key, value) => {
if (typeof value === 'string') {
return value.toLowerCase();
}
return value;
});
console.log(jsonString);
// '{"name":"john","age":30,"city":"new york"}'
Replacer array — only include specific keys:
const obj = { name: "John", age: 30, city: "New York", password: "secret" };
const jsonString = JSON.stringify(obj, ['name', 'age']);
console.log(jsonString);
// '{"name":"John","age":30}'
Practical — omit sensitive fields:
const user = { id: 1, name: "Alice", password: "secret", token: "abc123" };
const safeJson = JSON.stringify(user, (key, value) => {
if (key === 'password' || key === 'token') {
return undefined; // Omit
}
return value;
});
console.log(safeJson);
// '{"id":1,"name":"Alice"}'
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
color: #333;
line-height: 1.6;
}
h1 { color: #007bff; border-bottom: 3px solid #007bff; padding-bottom: 10px; }
h2 { color: #28a745; border-left: 4px solid #28a745; padding-left: 15px; margin-top: 30px; }
.demo-box {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
margin: 15px 0;
}
pre {
background: #1e1e1e;
color: #d4d4d4;
padding: 15px;
border-radius: 8px;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 0.9rem;
line-height: 1.8;
}
.keyword { color: #569cd6; }
.string { color: #ce9178; }
.number { color: #b5cea8; }
.function { color: #dcdcaa; }
.comment { color: #6a9955; }
.boolean { color: #569cd6; }
#output {
background: #e9ecef;
padding: 15px;
border-radius: 8px;
margin-top: 15px;
min-height: 40px;
font-family: 'Courier New', monospace;
font-size: 0.85rem;
border-left: 4px solid #007bff;
white-space: pre-wrap;
}
table {
width: 100%;
border-collapse: collapse;
margin: 15px 0;
}
th, td {
padding: 10px;
border: 1px solid #ddd;
text-align: left;
}
th { background: #007bff; color: white; }
tr:nth-child(even) { background: #f8f9fa; }
.btn {
padding: 10px 20px;
background: #007bff;
color: white;
border: none;
border-radius: 6px;
font-size: 1em;
font-weight: bold;
cursor: pointer;
margin: 5px;
transition: all 0.3s;
}
.btn:hover {
background: #0056b3;
transform: translateY(-2px);
}
.btn-success { background: #28a745; }
.btn-success:hover { background: #1e7e34; }
.btn-danger { background: #dc3545; }
.btn-danger:hover { background: #a71d2a; }
textarea {
width: 100%;
padding: 12px;
border: 2px solid #ddd;
border-radius: 6px;
font-family: 'Courier New', monospace;
font-size: 0.9rem;
min-height: 120px;
resize: vertical;
}
textarea:focus {
outline: none;
border-color: #007bff;
}
.json-display {
background: #1e1e1e;
color: #d4d4d4;
padding: 15px;
border-radius: 8px;
font-family: 'Courier New', monospace;
font-size: 0.85rem;
white-space: pre-wrap;
overflow-x: auto;
max-height: 300px;
overflow-y: auto;
margin: 10px 0;
}
</style>
</head>
<body>
<h1>JSON (JavaScript Object Notation)</h1>
<div class="demo-box">
<h2>1. JSON Data Types</h2>
<table>
<tr>
<th>Type</th>
<th>Example</th>
<th>Valid in JSON?</th>
</tr>
<tr>
<td>Object</td>
<td><code>{"name": "John"}</code></td>
<td>✅ Yes</td>
</tr>
<tr>
<td>Array</td>
<td><code>[1, 2, 3]</code></td>
<td>✅ Yes</td>
</tr>
<tr>
<td>String</td>
<td><code>"hello"</code></td>
<td>✅ Yes (double quotes only)</td>
</tr>
<tr>
<td>Number</td>
<td><code>42</code></td>
<td>✅ Yes</td>
</tr>
<tr>
<td>Boolean</td>
<td><code>true</code></td>
<td>✅ Yes</td>
</tr>
<tr>
<td>Null</td>
<td><code>null</code></td>
<td>✅ Yes</td>
</tr>
<tr>
<td>Single quotes</td>
<td><code>{'name': 'John'}</code></td>
<td>❌ Invalid</td>
</tr>
<tr>
<td>Undefined</td>
<td><code>undefined</code></td>
<td>❌ Invalid</td>
</tr>
<tr>
<td>Function</td>
<td><code>() => {}</code></td>
<td>❌ Invalid</td>
</tr>
<tr>
<td>Comments</td>
<td><code>// comment</code></td>
<td>❌ Invalid</td>
</tr>
</table>
</div>
<div class="demo-box">
<h2>2. JSON.parse()</h2>
<pre>
<span class="keyword">const</span> jsonString = <span class="string">'{"name": "John", "age": 30, "city": "New York"}'</span>;
<span class="keyword">const</span> obj = <span class="function">JSON.parse</span>(jsonString);
console.log(obj.name); <span class="comment">// "John"</span>
</pre>
</div>
<div class="demo-box">
<h2>3. JSON.parse() with Reviver</h2>
<pre>
<span class="keyword">const</span> jsonString = <span class="string">'{"name": "John", "age": 30}'</span>;
<span class="keyword">const</span> obj = <span class="function">JSON.parse</span>(jsonString, (key, value) => {
<span class="keyword">if</span> (<span class="keyword">typeof</span> value === <span class="string">'string'</span>) {
<span class="keyword">return</span> value.<span class="function">toUpperCase</span>();
}
<span class="keyword">return</span> value;
});
console.log(obj.name); <span class="comment">// "JOHN"</span>
</pre>
</div>
<div class="demo-box">
<h2>4. Interactive: JSON Parser</h2>
<p>Paste or type JSON below and click "Parse":</p>
<textarea id="jsonInput">{"name": "John", "age": 30, "city": "New York"}</textarea>
<div style="margin: 10px 0;">
<button class="btn btn-success" onclick="parseJson()">Parse JSON</button>
<button class="btn btn-danger" onclick="parseInvalidJson()">Try Invalid JSON</button>
<button class="btn" onclick="parseWithReviver()">Parse + Reviver (Uppercase)</button>
<button class="btn" onclick="clearJson()">Clear</button>
</div>
<div id="parseResult"></div>
</div>
<div class="demo-box">
<h2>5. JSON.stringify()</h2>
<pre>
<span class="keyword">const</span> obj = {name: <span class="string">"John"</span>, age: <span class="number">30</span>, city: <span class="string">"New York"</span>};
<span class="comment">// Compact</span>
<span class="function">JSON.stringify</span>(obj);
<span class="comment">// '{"name":"John","age":30,"city":"New York"}'</span>
<span class="comment">// Pretty (2-space indent)</span>
<span class="function">JSON.stringify</span>(obj, <span class="boolean">null</span>, <span class="number">2</span>);
</pre>
</div>
<div class="demo-box">
<h2>6. Interactive: JSON Stringifier</h2>
<p>Edit the object properties and stringify them:</p>
<div style="margin: 10px 0;">
<button class="btn btn-success" onclick="stringifyCompact()">Compact</button>
<button class="btn" onclick="stringifyPretty()">Pretty (2-space)</button>
<button class="btn" onclick="stringifyReplacer()">Replacer (Omit Password)</button>
<button class="btn" onclick="stringifyArrayFilter()">Only name, age</button>
</div>
<div id="stringifyResult"></div>
</div>
<div class="demo-box">
<h2>7. Complete Example — Object with Various Types</h2>
<pre>
<span class="keyword">const</span> obj = {
name: <span class="string">"John"</span>, <span class="comment">// ✅ Included</span>
age: <span class="number">30</span>, <span class="comment">// ✅ Included</span>
isActive: <span class="boolean">true</span>, <span class="comment">// ✅ Included</span>
address: <span class="boolean">null</span>, <span class="comment">// ✅ Included</span>
greet: <span class="keyword">function</span>() {}, <span class="comment">// ❌ Omitted</span>
nickname: <span class="boolean">undefined</span>, <span class="comment">// ❌ Omitted</span>
id: <span class="function">Symbol</span>(<span class="string">'id'</span>), <span class="comment">// ❌ Omitted</span>
created: <span class="keyword">new</span> <span class="function">Date</span>() <span class="comment">// ✅ As ISO string</span>
};
</pre>
</div>
<div class="demo-box">
<h2>8. Live Output — All Examples</h2>
<div id="output">Loading...</div>
</div>
<script>
// ============================================
// JSON — Live Demo
// ============================================
let results = [];
// 1. JSON.parse()
results.push('📌 JSON.parse():\n');
const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
const obj = JSON.parse(jsonString);
results.push(' Input: ' + jsonString);
results.push(' obj.name → ' + obj.name);
results.push(' obj.age → ' + obj.age);
results.push(' obj.city → ' + obj.city);
results.push('');
// 2. JSON.parse() with reviver
results.push('📌 JSON.parse() with Reviver:\n');
const jsonString2 = '{"name": "John", "age": 30, "city": "New York"}';
const obj2 = JSON.parse(jsonString2, (key, value) => {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
});
results.push(' Reviver uppercases strings:');
results.push(' obj2.name → ' + obj2.name);
results.push(' obj2.city → ' + obj2.city);
results.push(' obj2.age → ' + obj2.age + ' (number unchanged)');
results.push('');
// 3. Error handling
results.push('📌 Error Handling:\n');
try {
const invalidJson = '{"name": "John", "age": 30, "city": "New York"';
JSON.parse(invalidJson);
} catch (error) {
results.push(' Invalid JSON caught!');
results.push(' Error: ' + error.name + ' — ' + error.message);
}
results.push('');
// 4. JSON.stringify()
results.push('📌 JSON.stringify():\n');
const obj3 = { name: "John", age: 30, city: "New York" };
results.push(' Compact: ' + JSON.stringify(obj3));
results.push('');
// 5. Pretty print
results.push('📌 Pretty Print (2-space):\n');
results.push(JSON.stringify(obj3, null, 2).split('\n').map(line => ' ' + line).join('\n'));
results.push('');
// 6. Replacer function
results.push('📌 Replacer Function:\n');
const obj4 = { name: "John", age: 30, city: "New York" };
const jsonString4 = JSON.stringify(obj4, (key, value) => {
if (typeof value === 'string') {
return value.toLowerCase();
}
return value;
});
results.push(' Replacer lowercases strings:');
results.push(' ' + jsonString4);
results.push('');
// 7. Replacer array — only specific keys
results.push('📌 Replacer Array:\n');
const user = { id: 1, name: "Alice", password: "secret", token: "abc123", age: 25 };
results.push(' Full: ' + JSON.stringify(user));
results.push(' Only id, name: ' + JSON.stringify(user, ['id', 'name']));
results.push('');
// 8. Omit sensitive fields
results.push('📌 Omit Sensitive Fields:\n');
const safeJson = JSON.stringify(user, (key, value) => {
if (key === 'password' || key === 'token') {
return undefined;
}
return value;
});
results.push(' Safe: ' + safeJson);
results.push('');
// 9. What gets omitted
results.push('📌 What Gets Omitted in JSON.stringify():\n');
const complexObj = {
name: "John",
age: 30,
isActive: true,
address: null,
greet: function() {},
nickname: undefined,
id: Symbol('id'),
created: new Date('2024-01-15T10:30:00Z')
};
results.push(' Original keys: ' + Object.keys(complexObj).join(', '));
const serialized = JSON.stringify(complexObj);
results.push(' Serialized: ' + serialized);
results.push(' → Functions, undefined, and symbols are omitted');
results.push(' → Date becomes ISO string');
results.push('');
// 10. Nested JSON
results.push('📌 Nested JSON:\n');
const nested = {
user: {
name: "Alice",
address: {
city: "NYC",
zip: "10001"
}
},
hobbies: ["reading", "coding"]
};
results.push(' ' + JSON.stringify(nested, null, 2).split('\n').join('\n '));
results.push('');
// 11. Deep clone with JSON
results.push('📌 Deep Clone with JSON:\n');
const original = { a: 1, b: { c: 2 } };
const clone = JSON.parse(JSON.stringify(original));
clone.b.c = 99;
results.push(' Original: ' + JSON.stringify(original));
results.push(' Clone: ' + JSON.stringify(clone));
results.push(' → Deep clone works! Original unchanged ✅');
results.push('');
// 12. JSON limitations
results.push('📌 JSON Limitations:\n');
results.push(' ❌ Cannot serialize: functions, undefined, symbols, BigInt');
results.push(' ❌ Cannot serialize circular references');
results.push(' ❌ Loses Date objects (becomes strings)');
results.push(' ❌ Loses Map and Set (become {})');
results.push('');
// 13. Circular reference demo
results.push('📌 Circular Reference Error:\n');
const circular = { name: "test" };
circular.self = circular;
try {
JSON.stringify(circular);
} catch (error) {
results.push(' Error: ' + error.message);
}
document.getElementById('output').textContent = results.join('\n');
// ============================================
// Interactive: JSON Parser
// ============================================
function parseJson() {
const input = document.getElementById('jsonInput').value;
const result = document.getElementById('parseResult');
try {
const obj = JSON.parse(input);
result.innerHTML = `
<p style="color: #28a745; font-weight: bold;">✅ Parsed successfully!</p>
<div class="json-display">${JSON.stringify(obj, null, 2)}</div>
<p>Type: <code>${typeof obj}</code></p>
`;
} catch (error) {
result.innerHTML = `
<p style="color: #dc3545; font-weight: bold;">❌ Parse error</p>
<p><code>${error.name}: ${error.message}</code></p>
`;
}
}
function parseInvalidJson() {
document.getElementById('jsonInput').value = '{"name": "John", "age": 30, "city": "New York"';
parseJson();
}
function parseWithReviver() {
const input = document.getElementById('jsonInput').value;
const result = document.getElementById('parseResult');
try {
const obj = JSON.parse(input, (key, value) => {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
});
result.innerHTML = `
<p style="color: #28a745; font-weight: bold;">✅ Parsed with reviver (strings uppercased)</p>
<div class="json-display">${JSON.stringify(obj, null, 2)}</div>
`;
} catch (error) {
result.innerHTML = `
<p style="color: #dc3545; font-weight: bold;">❌ Parse error</p>
<p><code>${error.message}</code></p>
`;
}
}
function clearJson() {
document.getElementById('jsonInput').value = '';
document.getElementById('parseResult').innerHTML = '';
}
// ============================================
// Interactive: JSON Stringifier
// ============================================
const stringifyObj = {
id: 1,
name: "Alice",
age: 30,
password: "secret123",
email: "alice@example.com"
};
function stringifyCompact() {
const result = document.getElementById('stringifyResult');
result.innerHTML = `
<p><strong>Compact:</strong></p>
<div class="json-display">${JSON.stringify(stringifyObj)}</div>
`;
}
function stringifyPretty() {
const result = document.getElementById('stringifyResult');
result.innerHTML = `
<p><strong>Pretty (2-space):</strong></p>
<div class="json-display">${JSON.stringify(stringifyObj, null, 2)}</div>
`;
}
function stringifyReplacer() {
const result = document.getElementById('stringifyResult');
const safe = JSON.stringify(stringifyObj, (key, value) => {
if (key === 'password') return undefined;
return value;
}, 2);
result.innerHTML = `
<p><strong>Replacer (omits password):</strong></p>
<div class="json-display">${safe}</div>
`;
}
function stringifyArrayFilter() {
const result = document.getElementById('stringifyResult');
const filtered = JSON.stringify(stringifyObj, ['id', 'name', 'age'], 2);
result.innerHTML = `
<p><strong>Only id, name, age:</strong></p>
<div class="json-display">${filtered}</div>
`;
}
</script>
</body>
</html>
Quick Reference
JSON Data Types
| Type | Example | Valid? |
|---|---|---|
| Object | {"name": "John"} | ✅ Yes |
| Array | [1, 2, 3] | ✅ Yes |
| String | "hello" | ✅ Yes (double quotes) |
| Number | 42, 3.14 | ✅ Yes |
| Boolean | true, false | ✅ Yes |
| Null | null | ✅ Yes |
| Single quotes | {'a': 1} | ❌ Invalid |
| Undefined | undefined | ❌ Invalid |
| Function | () => {} | ❌ Invalid |
| Comments | // comment | ❌ Invalid |
| Trailing comma | {"a": 1,} | ❌ Invalid |
JSON Methods
| Method | Description | Example |
|---|---|---|
JSON.parse(str) | JSON string → object | JSON.parse('{"a":1}') → {a:1} |
JSON.parse(str, reviver) | With transformation | JSON.parse(str, (k,v) => ...) |
JSON.stringify(obj) | Object → JSON string | JSON.stringify({a:1}) → '{"a":1}' |
JSON.stringify(obj, null, 2) | Pretty print | 2-space indent |
JSON.stringify(obj, replacer) | With transformation | JSON.stringify(obj, (k,v) => ...) |
JSON.stringify(obj, array) | Only specific keys | JSON.stringify(obj, ['a', 'b']) |
What Gets Omitted in JSON.stringify()
| Value | Included? |
|---|---|
| String, number, boolean | ✅ Yes |
null | ✅ Yes |
undefined | ❌ Omitted |
| Function | ❌ Omitted |
| Symbol | ❌ Omitted |
Date | ✅ As ISO string |
Map, Set | ❌ Becomes {} |
| BigInt | ❌ Throws error |
Best Practices
✅ Do This:
// Always handle parse errors
try {
const data = JSON.parse(jsonString);
} catch (error) {
console.error('Invalid JSON:', error.message);
}
// Use a safe parse helper
function safeParse(str, fallback = null) {
try {
return JSON.parse(str);
} catch {
return fallback;
}
}
// Omit sensitive fields with replacer
const safeJson = JSON.stringify(user, (key, value) => {
if (key === 'password') return undefined;
return value;
});
// Use pretty print for debugging
JSON.stringify(obj, null, 2);
// Deep clone simple objects
const clone = JSON.parse(JSON.stringify(original));
// Validate types after parsing
if (typeof data.name === 'string') { }
❌ Don’t Do This:
// Don't parse without error handling
const data = JSON.parse(jsonString); // ❌ Throws if invalid
// Don't use single quotes in JSON
const bad = "{'name': 'John'}"; // ❌ Invalid JSON
// Don't trust untrusted JSON directly
eval('(' + jsonString + ')'); // ❌ SECURITY RISK!
// Don't use JSON.stringify for deep clone with complex types
const clone = JSON.parse(JSON.stringify(objWithDates)); // ⚠️ Dates become strings
// Don't forget circular references throw
const circular = {};
circular.self = circular;
JSON.stringify(circular); // ❌ TypeError
// Don't use JSON for sensitive data in URLs
// Passwords, tokens should not be in URLs
Common Pitfalls
| Pitfall | Problem | Solution |
|---|---|---|
| Single quotes | Invalid JSON | Use double quotes |
| Trailing commas | Invalid JSON | Remove them |
| No error handling | Crashes on invalid | Use try-catch |
| Circular reference | TypeError | Avoid or use custom replacer |
| Date objects | Becomes string | Parse with reviver |
undefined/functions | Silently omitted | Be aware of this |
| BigInt | TypeError | Convert to string first |
eval() instead of parse() | Security risk | Use JSON.parse() |
JSON vs JavaScript Object
// JavaScript object (NOT valid JSON)
const jsObj = {
name: 'John', // Single quotes
greet() { }, // Method
age: 30, // Trailing comma OK
};
// Valid JSON
const json = '{"name": "John", "age": 30}';
Practical: Fetch API Example
async function fetchUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) throw new Error('Network error');
const user = await response.json(); // Parse JSON response
console.log(user.name);
return user;
} catch (error) {
console.error('Failed to fetch user:', error.message);
}
}
async function createUser(user) {
try {
const response = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user) // Serialize to JSON
});
return await response.json();
} catch (error) {
console.error('Failed to create user:', error.message);
}
}
Pro Tip: JSON is the universal language for data exchange on the web. Always use JSON.parse() (not eval()) for security. Always wrap parsing in try-catch — JSON from external sources can be invalid. Use reviver to transform dates on parse and replacer to omit sensitive fields on stringify. Remember: JSON is strict — double quotes only, no comments, no trailing commas, no functions. And for deep cloning, JSON.parse(JSON.stringify(obj)) works — but loses Dates, Maps, Sets, and functions. For production, consider structuredClone() (modern) or libraries like Lodash!
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!