JavaScript: 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.
1. 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 |
JSON
{
"name": "Alice",
"age": 25,
"skills": ["HTML", "CSS", "JS"],
"address": {
"city": "New York",
"zip": "10001"
},
"active": true,
"spouse": null
}
⚠️ Note: No single quotes in JSON! The most common beginner mistake is writing
'key' or 'value' — this is valid in JS but illegal in JSON.
2. JSON.stringify()
JSON.stringify() converts a JS value into a JSON string — serialization.
HTML
<!-- Script tag -->
<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
▶ Try it Yourself💡 Tip: Note:
undefined, functions, and Symbols are ignored during serialization (properties disappear from objects, become null in arrays). Date objects are converted to ISO strings.
3. JSON.parse()
JSON.parse() converts a JSON string back into a JS value — deserialization.
HTML
<!-- Script tag -->
<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
▶ Try it Yourself4. 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) |
💡 Tip: Easy way to remember: JSON is "a string version of JS objects with strict validation." It's not an object — it's text. You need
parse to turn it into an object you can work with.
▶ Example: Common JSON Errors
▶ Try it Yourself💡 Tip: The three most common JSON errors: single quotes, trailing commas, and
undefined. When debugging JSON issues, paste it into the browser console with JSON.parse() — the error message will pinpoint the exact location.
❓ FAQ
Q What is the difference between JSON and JavaScript objects?
A JSON is a text data format where keys must use double quotes, and values can only be strings, numbers, booleans,
null, arrays, or objects. A JS object is an in-memory data structure where keys may be unquoted and values can be functions, undefined, Date, and so on. The two are not the same thing; when transmitting, you need to convert a JS object into a JSON string with JSON.stringify.Q What should I do when
JSON.parse throws an Unexpected token error?A The most common cause is that the string is not valid JSON, for example using single quotes, keys without double quotes, a trailing comma, or comments. First use
JSON.stringify to check in reverse, or paste the string into a JSON validation tool to locate the error position, then fix it and call JSON.parse again.Q How do I convert JSON into an object or array in JavaScript?
A Use
JSON.parse(jsonString) to convert JSON text into the corresponding JS object or array; for example, JSON.parse('{"a":1}') returns an object. If the data comes from fetch, you can first await res.text() and then JSON.parse, or simply use res.json() directly.📖 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
📝 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.