01 / 21
{ "k": "v" }

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

JSON String ' { "name" : "Alice" , "age" : 25 , "active" : true } ' typeof: "string" parse stringify JS Object { name : "Alice" , age : 25 , active : true } typeof: "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

JSON String "{ ... }" JS Value { ... } JSON.parse() JSON.stringify() Two inverse operations: string ⇆ value

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

Original Object { name: "Alice", greet: function(){}, secret: undefined, id: Symbol("x"), count: NaN, big: Infinity } stringify Result { "name": "Alice", // greet: DROPPED // secret: DROPPED // id: DROPPED "count": null, "big": null }

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'?

Question 2 of 5

Which of the following is valid JSON?

Question 3 of 5

What happens when you call JSON.stringify() on an object that contains a function as a property value?

Question 4 of 5

To save a JavaScript object to localStorage and later retrieve it, which sequence is correct?

Question 5 of 5

What is the purpose of the third argument (space) in JSON.stringify(value, replacer, space)?