Course: JavaScript Intermediate
Lesson 13: JSON
Level
Intermediate
Estimated Reading Time
10–15 minutes
Goal
By the end of this lesson, the learner will be able to:
- Explain what JSON is and how it differs from a JavaScript object literal
- Use
JSON.stringifyto convert a JavaScript value to a JSON string - Use
JSON.parseto convert a JSON string back into a JavaScript value
Frontend Development Context
JSON (JavaScript Object Notation) is the universal format for exchanging data between clients and servers. When your browser requests data from an API, the response almost always arrives as a JSON string. When you send data to a server, you typically serialize it as JSON first. Understanding JSON is not optional for frontend development — it is the lingua franca of web APIs.
Knowing the difference between a JavaScript object and a JSON string also prevents a category of bugs where you try to access properties on a string or accidentally serialize something that is not serializable. Every time you use fetch, localStorage, or a file-based data source, JSON is involved.
Explanation
JSON is a text format that represents structured data. It looks a lot like a JavaScript object, but there are key differences. In JSON, all property names must be double-quoted strings. Values can be strings, numbers, booleans, arrays, objects, or null. JSON cannot represent functions, undefined, Symbol, or circular references.
JSON.stringify(value) converts a JavaScript value into a JSON string. This is serialization. The resulting string can be stored in localStorage, sent over a network, or written to a file. Properties with undefined values, functions, and Symbols are silently omitted during stringification.
JSON.parse(string) converts a JSON string back into a JavaScript value. This is deserialization (or parsing). If the string is not valid JSON, JSON.parse throws a SyntaxError. Wrapping the call in a try/catch is the safe approach when the input might be malformed.
JSON.stringify accepts optional arguments: a replacer (to filter or transform properties) and a space argument (to format the output with indentation for readability). Passing 2 as the third argument produces pretty-printed JSON.
Because JSON is a string format, comparing two JSON values directly is a string comparison — "{"a":1}" and "{ "a": 1 }" would not be equal even if they represent the same data structure. Parse both before comparing.
Code Example
This example converts a JavaScript object to JSON and back, shows what gets omitted, and handles parse errors.
const lesson = {
id: 13,
title: "JSON",
level: "Intermediate",
completed: false,
tags: ["data", "api", "serialization"],
getLabel: function () { return this.title; } // functions are not JSON-serializable
};
// Serialize to JSON string
const jsonString = JSON.stringify(lesson);
console.log(jsonString);
// {"id":13,"title":"JSON","level":"Intermediate","completed":false,"tags":["data","api","serialization"]}
// Note: getLabel is omitted — functions are not valid JSON
// Pretty-print with indentation
const pretty = JSON.stringify(lesson, null, 2);
console.log(pretty);
// {
// "id": 13,
// "title": "JSON",
// ...
// }
// Parse JSON string back to a JavaScript object
const parsed = JSON.parse(jsonString);
console.log(parsed.title); // "JSON"
console.log(parsed.tags[1]); // "api"
// Safe parsing with try/catch
function safeParse(str) {
try {
return JSON.parse(str);
} catch {
console.error("Invalid JSON:", str);
return null;
}
}
console.log(safeParse('{"valid": true}')); // { valid: true }
console.log(safeParse("not valid json")); // null
Code Explanation
JSON.stringify(lesson) converts the object to a compact JSON string. The getLabel function is silently omitted because functions cannot be represented in JSON. All other properties (strings, numbers, booleans, arrays) are included.
JSON.stringify(lesson, null, 2) passes null as the replacer (meaning no filtering) and 2 as the indentation level. The result is a human-readable, formatted JSON string — useful for debugging and logging.
JSON.parse(jsonString) converts the string back to a JavaScript object. You can then access properties with dot notation or bracket notation as normal. Note that parsed.getLabel is undefined because functions were never included in the JSON string.
safeParse wraps JSON.parse in a try/catch. When the input is invalid JSON, JSON.parse throws a SyntaxError. The catch block logs the error and returns null as a safe default. Always use this pattern when parsing data from external sources where the format cannot be guaranteed.
Pattern Highlights
✅ Positive Pattern: Wrap
JSON.parsein atry/catchwhenever the source is untrusted — API responses with errors, user input, or corrupted localStorage data can all produce invalid JSON strings.
⚠️ Neutral Note:
JSON.stringifysilently drops functions,undefined, and Symbols. If you expect a property to appear in the output and it does not, check whether its value is one of these non-serializable types.
❌ Negative Pattern: Do not compare two JSON strings directly to check if two objects have the same structure. String equality depends on formatting (spaces, key order). Parse both strings first, then compare properties.
Common Mistakes
Mistake 1: Accessing properties on a JSON string instead of the parsed object
Treating the raw JSON string like an object.
const json = '{"name":"Alex","score":90}';
console.log(json.name); // undefined — json is a string, not an object
You must call JSON.parse(json) first to get an object whose properties you can access.
Mistake 2: Using single quotes in a JSON string
Writing JSON by hand with single-quoted property names.
const badJson = "{'name': 'Alex'}"; // invalid JSON — single quotes are not allowed
JSON.parse(badJson); // SyntaxError: Unexpected token '
JSON requires double quotes for all strings, including property names. Single quotes are valid JavaScript syntax in object literals but are not valid JSON.
Mistake 3: Assuming JSON.stringify produces a stable key order
Relying on the order of keys in the output for comparison or hashing.
const a = { x: 1, y: 2 };
const b = { y: 2, x: 1 };
console.log(JSON.stringify(a) === JSON.stringify(b)); // false — key order differs
JSON.stringify preserves insertion order, so objects with the same properties in different orders produce different strings. For comparing data equality, use a proper deep-equal utility rather than string comparison.
Quick Recap
- JSON is a text format — it looks like a JavaScript object but all property names and string values must use double quotes
JSON.stringify(value)converts a JavaScript value to a JSON string; functions,undefined, and Symbols are omittedJSON.parse(string)converts a JSON string back to a JavaScript value; it throws aSyntaxErrorif the input is invalid- Always wrap
JSON.parsein atry/catchwhen the source is external or untrusted