JSON.parse &
JSON.stringify
Learn to serialize JavaScript objects into JSON strings and parse JSON strings back into usable data structures.
JavaScript
What is JSON?
JSON stands for JavaScript Object Notation. It is a lightweight, text-based data format that both humans and machines can read easily. Despite the name, JSON is language-independent: APIs, databases, and config files all use it.
JSON String vs JS Object
Why JSON Matters
APIs
Nearly every web API sends and receives data as JSON over HTTP.
Storage
localStorage only stores strings: you must stringify objects before saving.
Config
Files like package.json and tsconfig.json power the JS ecosystem.
The JSON.parse Method
const obj = JSON.parse(text, reviver?);
text
A valid JSON string to convert into a JavaScript value.
reviver (optional)
A function called for each key-value pair, letting you transform values during parsing.
The JSON.stringify Method
const str = JSON.stringify(value, replacer?, space?);
value
The JavaScript value (object, array, etc.) to convert into a JSON string.
replacer
A function or array that filters/transforms which properties are included.
space
Number (0-10) or string for indentation: makes output human-readable.
parse vs stringify
How to Apply These Methods
1
Identify the direction. Are you receiving text (parse) or sending data out (stringify)?
2
Validate the input. If parsing, ensure the string is valid JSON. Wrap in try...catch to handle errors gracefully.
3
Call the method. Use JSON.parse(str) or JSON.stringify(obj) as needed.
4
Use optional parameters. Add a reviver to transform during parse, or a replacer / space to control stringify output.
Example 1: Basic Parse
const jsonStr = '{ "name":"Alice","age":25}'; const user = JSON.parse(jsonStr); console.log(user.name); // "Alice" console.log(user.age); // 25 console.log(typeof user); // "object"
Example 2: Basic Stringify
const product = { id: 42, title: "Widget", inStock: true }; const json = JSON.stringify(product); // '{ "id":42,"title":"Widget","inStock":true}' console.log(typeof json); // "string"
Example 3: localStorage Round-Trip
const settings = { theme: "dark", fontSize: 16 }; // Save: stringify before storing localStorage.setItem( "prefs", JSON.stringify(settings) ); // Load: parse after retrieving const loaded = JSON.parse( localStorage.getItem("prefs") ); console.log(loaded.theme); // "dark"
Advanced: The Reviver Function
const json = '{ "date":"2024-01-15T00:00:00Z"}'; const obj = JSON.parse(json, (key, value) => { if (key === "date") return new Date(value); return value; }); console.log(obj.date instanceof Date); // true
What Gets Lost in Stringify
Bonus: Deep Clone Pattern
const original = { a: { b: 1 } }; // Deep clone via JSON round-trip const clone = JSON.parse(JSON.stringify(original)); clone.a.b = 99; console.log(original.a.b); // 1 (unchanged!) console.log(clone.a.b); // 99
Common Mistakes
Single Quotes in JSON
JSON requires double quotes for keys and string values. {'name':'Alice'} is invalid JSON and will throw a SyntaxError.
Parsing Non-Strings
Passing an object to JSON.parse() instead of a string causes errors. Always confirm the input is a string first.
No try/catch
Parsing untrusted input without try...catch will crash your app if the JSON is malformed. Always handle the error.
Summary Comparison
| JSON.parse() | JSON.stringify() | |
|---|---|---|
| Direction | String → Value | Value → String |
| Input | JSON string | JS value |
| Output | JS value | JSON string |
| Optional Param | reviver | replacer, space |
| Throws On | Invalid JSON | Circular references |
| Common Use | API responses, loading data | Saving, sending, cloning |
Question 1 of 5
What does JSON.parse() return when given the string '42'?
JSON.parse('42') returns the number 42. JSON is not limited to objects: any valid JSON value (string, number, boolean, null, array, object) can be parsed.
Question 2 of 5
Which of the following is valid JSON?
JSON requires double-quoted keys and string values. Option A has unquoted keys, B uses single quotes, and D contains undefined which is not a valid JSON value.
Question 3 of 5
What happens when you call JSON.stringify() on an object that contains a function as a property value?
JSON.stringify silently drops properties whose values are functions, undefined, or Symbols. No error is thrown: the key simply disappears from the result.
Question 4 of 5
To save a JavaScript object to localStorage and later retrieve it, which sequence is correct?
localStorage only stores strings. You must JSON.stringify before saving and JSON.parse when loading to recover the original object structure.
Question 5 of 5
What is the purpose of the third argument (space) in JSON.stringify(value, replacer, space)?
The space parameter controls indentation. Passing 2 adds 2-space indentation to each level. Passing a string (e.g., "\t") uses that string for each indent level. Option C describes the replacer, not space.