JSON.strigify() vs JSON.parse()

javascript dev.to

🧠 JSON.stringify vs JSON.parse β€” Deep Dive

In JavaScript, these two APIs convert between JavaScript values and JSON text:

JSON.stringify(value) β†’ JS value ➜ JSON string
JSON.parse(text) β†’ JSON string ➜ JS value

Think:

stringify = serialize (object β†’ text)
parse = deserialize (text β†’ object)

βš™οΈ 1) JSON.stringify β€” How it works internally
🎯 Basic

const obj = { name: "Ashish", age: 25 };
const str = JSON.stringify(obj);
// '{"name":"Ashish","age":25}'
Enter fullscreen mode Exit fullscreen mode

πŸ”¬ Internal Steps (conceptual)

Input JS value
  ↓
Walk the structure (recursive)
  ↓
Convert primitives to JSON tokens
  ↓
Build a valid JSON string
Enter fullscreen mode Exit fullscreen mode

Objects β†’ { "key": value }
Arrays β†’ [ ... ]
Strings β†’ quoted with escaping
Numbers/booleans β†’ as-is

🧩 Examples (important cases)
βœ… Nested objects

JSON.stringify({ a: 1, b: { c: 2 } });
// '{"a":1,"b":{"c":2}}'
Enter fullscreen mode Exit fullscreen mode

⚠️ undefined, functions, symbols

JSON.stringify({
  a: undefined,
  b: function () {},
  c: Symbol("x"),
  d: 1
});
// '{"d":1}'
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ These are omitted in objects

⚠️ In arrays

JSON.stringify([1, undefined, function(){}, 3]);
// '[1,null,null,3]'
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ They become null in arrays

⚠️ Dates

JSON.stringify({ d: new Date("2024-01-01") });
// '{"d":"2024-01-01T00:00:00.000Z"}'
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Uses toJSON() β†’ ISO string

❌ Circular references

const a = {};
a.self = a;

JSON.stringify(a); // ❌ TypeError
Enter fullscreen mode Exit fullscreen mode

πŸ”§ Advanced: replacer & space
Replacer (filter/transform)

JSON.stringify({ a: 1, b: 2 }, ["a"]);
// '{"a":1}'
Enter fullscreen mode Exit fullscreen mode

or function:


JSON.stringify({ a: 1, b: 2 }, (key, value) =>
  key === "b" ? undefined : value
);
// '{"a":1}'
Enter fullscreen mode Exit fullscreen mode

Pretty print

JSON.stringify(obj, null, 2);
Enter fullscreen mode Exit fullscreen mode

βš™οΈ 2) JSON.parse β€” How it works internally
🎯 Basic

const str = '{"name":"Ashish","age":25}';
const obj = JSON.parse(str);
// { name: "Ashish", age: 25 }
Enter fullscreen mode Exit fullscreen mode

πŸ”¬ Internal Steps

Input JSON string
  ↓
Lexer + Parser (strict JSON grammar)
  ↓
Build JS objects/arrays/primitives
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ JSON must be valid:

Double quotes required
No trailing commas
🧩 Examples
βœ… Array

JSON.parse('[1, 2, 3]');
// [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

❌ Invalid JSON

JSON.parse("{ name: 'Ashish' }"); // ❌ Error
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Must be:

JSON.parse('{ "name": "Ashish" }');
Enter fullscreen mode Exit fullscreen mode

πŸ”§ Advanced: reviver

Transform values during parsing:


const obj = JSON.parse('{"date":"2024-01-01"}', (key, value) => {
  if (key === "date") return new Date(value);
  return value;
});
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Convert string β†’ Date object

πŸ” Round Trip Example
const original = { x: 1, y: [2, 3] };

const str = JSON.stringify(original);
const copy = JSON.parse(str);

console.log(copy); // deep copy-like
⚠️ Important Limitations
❌ Loses functions

JSON.stringify({ fn: () => {} });
// '{}'
Enter fullscreen mode Exit fullscreen mode

❌ Loses undefined

JSON.stringify({ a: undefined });
// '{}'
Enter fullscreen mode Exit fullscreen mode

❌ Loses class/prototype

class User {
  constructor(name) {
    this.name = name;
  }
}

const u = new User("A");
const copy = JSON.parse(JSON.stringify(u));

copy instanceof User; // false ❌
Enter fullscreen mode Exit fullscreen mode

βš–οΈ stringify vs parse
Feature stringify parse
Direction JS β†’ JSON string JSON string β†’ JS
Output string object/array
Errors circular refs invalid JSON
Customization replacer reviver
🧠 Real-World Use Cases
πŸ“¦ API communication

fetch("/api", {
  method: "POST",
  body: JSON.stringify(data)
});
Enter fullscreen mode Exit fullscreen mode

πŸ’Ύ Local storage

localStorage.setItem("user", JSON.stringify(user));
const user = JSON.parse(localStorage.getItem("user"));
Enter fullscreen mode Exit fullscreen mode

πŸ” Deep clone (limited)

const clone = JSON.parse(JSON.stringify(obj));
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Works only for simple data

🧭 Mental Model

stringify β†’ β€œconvert JS to transportable text”
parse β†’ β€œrebuild JS from text”

🎯 Final Takeaways
JSON.stringify serializes JS β†’ JSON string
JSON.parse deserializes JSON β†’ JS object
They are inverse operations
But not perfect (data loss for functions, prototypes, etc.)

Source: dev.to

arrow_back Back to Tutorials