JavaScript JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format. Think of it as a standardized shipping box — no matter what you put inside, the packaging follows a universal spec so the recipient knows exactly how to unpack it. Front-end/back-end communication, configuration files, local storage — JSON is everywhere.
JSON Syntax Rules
JSON looks a lot like a JS object literal, but the rules are stricter:
| Rule | Description |
|---|---|
| Keys must use double quotes | "name" ✅ name ❌ 'name' ❌ |
| String values must use double quotes | "hello" ✅ 'hello' ❌ |
| No trailing commas | {"a":1,} ❌ |
| Limited value types | string, number, boolean, null, object, array |
| Not allowed | undefined, functions, comments |
{
"name": "Alice",
"age": 25,
"skills": ["HTML", "CSS", "JS"],
"address": {
"city": "New York",
"zip": "10001"
},
"active": true,
"spouse": null
}
'key' or 'value' — this is valid in JS but illegal in JSON.
JSON.stringify()
JSON.stringify() converts a JS value into a JSON string — serialization.
<script>
JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)
</script>
| Parameter | Description |
|---|---|
value |
The value to serialize |
replacer |
Filter or transform — a function or array |
space |
Indentation — number or string, for pretty-printing |
Example: Serialization and Formatting
<div id="output" style="white-space: pre; font-family: monospace; padding: 10px; border: 1px solid #ccc;"></div>
<script>
const student = {
name: 'Bob',
age: 20,
scores: [95, 88, 92],
active: true,
grade: undefined,
birthday: new Date()
};
const output = document.getElementById('output');
const plain = JSON.stringify(student);
output.textContent = 'Compact output:\n' + plain + '\n\n';
const pretty = JSON.stringify(student, null, 2);
output.textContent += 'Pretty output:\n' + pretty + '\n\n';
const filtered = JSON.stringify(student, ['name', 'scores'], 2);
output.textContent += 'Only name and scores:\n' + filtered;
</script>
undefined, functions, and Symbols are ignored during serialization (properties disappear from objects, become null in arrays). Date objects are converted to ISO strings.
JSON.parse()
JSON.parse() converts a JSON string back into a JS value — deserialization.
<script>
JSON.parse(text)
JSON.parse(text, reviver)
</script>
| Parameter | Description |
|---|---|
text |
The JSON string |
reviver |
A transform function applied to each key-value pair |
Example: Deserialization
<div id="output" style="white-space: pre; font-family: monospace; padding: 10px; border: 1px solid #ccc;"></div>
<script>
const output = document.getElementById('output');
const jsonStr = '{"name":"Charlie","age":30,"hobbies":["reading","coding"]}';
const obj = JSON.parse(jsonStr);
output.textContent = 'Parsed result:\n';
output.textContent += 'Name: ' + obj.name + '\n';
output.textContent += 'Age: ' + obj.age + '\n';
output.textContent += 'Hobbies: ' + obj.hobbies.join(', ') + '\n\n';
const arr = JSON.parse('[1, 2, 3, 4, 5]');
output.textContent += 'Parsed array: ' + arr + '\n';
output.textContent += 'Array sum: ' + arr.reduce(function(a, b) { return a + b; }, 0);
</script>
JSON vs JS Object
| Comparison | JSON | JS Object |
|---|---|---|
| Nature | String (text) | In-memory data structure |
| Key quotes | Double quotes required | Omissible (for valid identifiers) |
| Value types | Limited (6 types) | Any type |
| Trailing commas | Not allowed | Allowed |
| Comments | Not allowed | Supported (via tooling) |
parse to turn it into an object you can work with.
Example: Common JSON Errors
<div id="output" style="white-space: pre; font-family: monospace; padding: 10px; border: 1px solid #ccc;"></div>
<script>
const output = document.getElementById('output');
function tryParse(str, label) {
try {
JSON.parse(str);
output.textContent += label + ': ✅ Success\n';
} catch (e) {
output.textContent += label + ': ❌ ' + e.message + '\n';
}
}
tryParse("{'name':'Tom'}", 'Single-quote key');
tryParse('{"name":"Tom",}', 'Trailing comma');
tryParse('{"name":undefined}', 'undefined value');
tryParse('{"name":"Tom"}', 'Valid JSON');
tryParse('{"a":1,"b":2}', 'Valid JSON (no spaces)');
</script>
undefined. When debugging JSON issues, paste it into the browser console with JSON.parse() — the error message will pinpoint the exact location.
📖 Summary
- JSON is a string-based data format — keys must be double-quoted, no trailing commas, limited value types
JSON.stringify()serializes,JSON.parse()deserializes — they are inverse operationsundefined, functions, and Symbols are ignored or becomenullduring serialization- The
spaceparameter inJSON.stringifymakes output readable; thereplacerparameter filters fields - Parsing invalid JSON throws an exception — always wrap it in
try/catch
❓ FAQ
Q: Why does
JSON.stringify(NaN)returnnull? A: The JSON spec has noNaN,Infinity, or-Infinity— they all becomenullduring serialization. If you need to preserve these values, use a customreplacerfunction.
Q: Can
JSON.parseparse JS object literals? A: No.JSON.parse('{}')works, butJSON.parse('{a:1}')throws an error — the key lacks double quotes. JSON syntax is stricter than JS object literals.
Q: Can you write comments in JSON? A: Standard JSON does not support comments. If needed, use a field like
"_comment": "description"as a workaround, though this isn't a formal convention.
📝 Exercises
- Basic: Create an array of 3 student objects and format the output with
JSON.stringify(2-space indent). - Intermediate: Write a
safeParse(str)function that wrapsJSON.parseintry/catch, returning the result on success ornullwith an error message on failure. - Challenge: Build a "local notepad" — use
promptfor input, save tolocalStoragewithJSON.stringify, and load/display it on page load withJSON.parse.



