JSON: stringify and parse

JavaScript ES2024 · ✓ verified by execution on 2026-08-15

When building web applications, you frequently need to transmit data over the network or save it to a database. The challenge is that JavaScript objects exist dynamically in your computer’s memory. You cannot send a living memory structure over an HTTP request. You must convert it into a flat, universally understood format.

This is exactly what JSON (JavaScript Object Notation) does. JSON is a lightweight text-based data format. Although it looks identical to JavaScript objects, it is fundamentally just a string of characters.

Creating JSON with stringify

To convert a JavaScript object into a JSON string, use the JSON.stringify() method. This process is often called “serialization.”

javascript
const data = { user: 'Alice', age: 25 };
const jsonString = JSON.stringify(data);

console.log(typeof jsonString);
console.log(jsonString);
Output
string
{"user":"Alice","age":25}

The output string is very compact, which is excellent for saving bandwidth, but terrible for human readability. Thankfully, JSON.stringify() accepts an optional third argument called space that automatically indents the output.

javascript
const data = { user: 'Alice', age: 25 };
// The second argument (replacer) is null, and the third is the indent size
console.log(JSON.stringify(data, null, 2));
Output
{
  "user": "Alice",
  "age": 25
}

Reading JSON with parse

When your application receives a JSON string from a server or file, it’s just raw text. To interact with the properties inside, you must turn it back into a JavaScript object. This process is called “deserialization” and is handled by JSON.parse().

javascript
const rawData = '{"user":"Bob","role":"admin"}';
const parsedObj = JSON.parse(rawData);

console.log(parsedObj.role);
Output
admin

It is incredibly important to note that JSON.parse() expects perfectly formatted JSON. If the string is malformed—for example, missing quotes around keys, or containing a trailing comma—the parser will instantly throw a SyntaxError and crash your application.

javascript
try {
  JSON.parse('{ invalid json }');
} catch (e) {
  console.log(e.name); // Caught the crash!
}
Output
SyntaxError

The Data Loss Pitfall

A common misconception is that JSON.stringify() creates a flawless, exact duplicate of your JavaScript objects. It does not.

JSON was designed to be a universal data-interchange format, meaning it only supports fundamental data types that exist across all programming languages: strings, numbers, booleans, arrays, and plain objects. It has no concept of functions, undefined, Symbols, or Dates.

When JSON.stringify() encounters something it doesn’t understand, it behaves ruthlessly: it either drops the property entirely or corrupts it.

Predict the output javascript

Read the code. What exactly will it print? Commit to an answer before you look.

const config = { 
  theme: 'dark', 
  cacheData: undefined, 
  onClick: () => { console.log('Click'); } 
};

console.log(JSON.stringify(config));
Output
{"theme":"dark"}

As you can see, both the undefined variable and the function were completely erased from the resulting string. If you were to pass that string back through JSON.parse(), those properties would be gone forever.

javascript · visualize
const user = {
  name: "Alice",
  age: 30,
  onLogin: function() { return true; },
  sessionKey: undefined
};
const result = JSON.stringify(user);

JS Object (Memory) name: "Alice" age: 30 onLogin: function() {...} sessionKey: undefined stringify() JSON String {" "name": "Alice", "age": 30 }" (dropped)
Visualizing serialization data loss. Functions and undefined are stripped during stringify.

When building modern applications, always remember that JSON is purely for data. You cannot serialize behavior (functions), and you must be careful when relying on missing values.

Check yourself

What does JSON.stringify() do?

Reveal answer

It converts a JavaScript object or value into a JSON string. — JSON.stringify() takes a JavaScript memory structure and serializes it into a raw string.

What happens to `undefined` values when an object is passed to JSON.stringify()?

Reveal answer

They are completely omitted from the resulting JSON string. — Keys with undefined values, as well as functions, are completely ignored and stripped out of the final JSON string.

Why is it a good idea to wrap JSON.parse() in a try/catch block?

Reveal answer

Because JSON.parse() throws a SyntaxError if the string is not perfectly valid JSON. — If a string is malformed, JSON.parse() throws a synchronous SyntaxError which will crash your program if uncaught.

What data type is returned by `JSON.parse('{"status": "ok"}')`?

Reveal answer

An Object — JSON.parse evaluates the string and constructs an in-memory JavaScript Object.

Challenges

🐞 Bug Hunt +15 XP

The `safeParse` function is supposed to return the parsed JavaScript object if the string is valid JSON, or `null` if the string is invalid. Right now, it crashes on invalid input. Fix the function using a `try/catch` block.

This code runs. It just does the wrong thing. Read it, find the defect, fix it — the tests below decide when you are right.

javascript
  • Test 1 (input: "{\"name\": \"Alice\"}") — expects "{\"name\":\"Alice\"}"
  • Test 2 (input: "{ invalid json }") — expects "null"
Need a hint? (−25% XP)

Wrap the `JSON.parse` call in a `try {} catch (e) {}` block.

Show solution (0 XP)
import fs from 'node:fs';
const input = fs.readFileSync(0, 'utf-8').trim();

function safeParse(jsonStr) {
  try {
    return JSON.parse(jsonStr);
  } catch (e) {
    return null;
  }
}

console.log(JSON.stringify(safeParse(input)));

Challenge 2 +10 XP

Write a function `formatData(obj)` that returns the given object as a JSON string indented with exactly 4 spaces.

javascript
  • Test 1 (input: "{\"a\":1}") — expects "{\n \"a\": 1\n}"
Need a hint? (−25% XP)

Pass `null` as the second argument, and `4` as the third argument to `JSON.stringify`.

Show solution (0 XP)
import fs from 'node:fs';
const obj = JSON.parse(fs.readFileSync(0, 'utf-8'));

function formatData(obj) {
  return JSON.stringify(obj, null, 4);
}

console.log(formatData(obj));