# JSON Handling

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Data Handling
Source: https://www.devtutorials.ai/learn/javascript/data-handling/json-handling

> What JSON is and how it differs from a JavaScript object, JSON structure, JSON.stringify() with indentation, JSON.parse(), the values JSON cannot carry, replacers, revivers and toJSON, and the common JSON errors and how to parse safely.

## What Is JSON?

**JSON** (JavaScript Object Notation) = a **text** format for storing and sending data.

- It looks like a JavaScript object, but it is a plain string.
- `JSON.stringify(value)` turns a value into JSON text.
- `JSON.parse(text)` turns JSON text back into a value.

**Simple lesson:** only text can travel between programs. JSON is the text form of your data.

### A Real-World Example

When you press **Place order**, the page turns the cart into JSON text and sends it to the server.
The server sends back JSON text like `{"orderId":5012,"status":"paid"}`.
The page parses it and shows **Order 5012 is paid**.

<figure className="ts-fig">
  <svg viewBox="0 0 560 170" role="img" aria-label="An object box turns into a text strip by stringify, travels to a server, and comes back by parse into an object again." width="100%">
    <rect x="0" y="0" width="560" height="170" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="20" y="50" width="120" height="60" rx="10" fill="#eff6ff" stroke="#2563eb" />
    <text x="80" y="76" textAnchor="middle" fontSize="12" fill="#1e40af">object</text>
    <text x="80" y="94" textAnchor="middle" fontSize="11" fontFamily="monospace" fill="#1e40af">&#123; id: 5012 &#125;</text>
    <rect x="420" y="50" width="120" height="60" rx="10" fill="#1e3a8a" />
    <text x="480" y="85" textAnchor="middle" fontSize="12" fill="#ffffff">Server</text>
    <text x="280" y="40" textAnchor="middle" fontSize="11" fill="#475569">JSON.stringify →</text>
    <text x="280" y="140" textAnchor="middle" fontSize="11" fill="#475569">← JSON.parse</text>
    <rect y="68" width="130" height="24" rx="4" fill="#fefce8" stroke="#ca8a04">
      <animate attributeName="x" values="145;285;145" keyTimes="0;0.5;1" dur="3s" repeatCount="indefinite" />
    </rect>
    <text y="85" textAnchor="middle" fontSize="11" fontFamily="monospace" fill="#854d0e">&#123;"id":5012&#125;<animate attributeName="x" values="210;350;210" keyTimes="0;0.5;1" dur="3s" repeatCount="indefinite" /></text>
  </svg>
  <figcaption>Data becomes text to travel, and text becomes data again.</figcaption>
</figure>

Some boxes throw on purpose to show real JSON errors. Their titles say so.

## What You Will Learn

1. What JSON is, and how it differs from an object.
2. JSON structure: pairs, objects, arrays and nesting.
3. `JSON.stringify()` (with indentation) and `JSON.parse()`.
4. What JSON cannot carry, and replacers, revivers and `toJSON`.
5. Common JSON errors, and parsing safely with `try`/`catch`.

## Introduction to JSON

### What is JSON?

JSON uses the same `{ }`, `[ ]` and `:` as objects, but it is **text**. `typeof` says `string`, so `json.name` does not work.

```js runnable title="JSON is a string that describes data"
const json = '{"name":"Asha","city":"Chennai","orders":3}';

console.log(json);
console.log(typeof json);
console.log(json.length);
```

Expected output:

```text
{"name":"Asha","city":"Chennai","orders":3}
string
43
```

### Why JSON is used

Browsers, servers and apps exchange data. Only text can travel, and every language can read JSON.

```js runnable title="Data becomes text to travel, and text becomes data again"
const order = { id: 5012, items: ["pen", "notebook"], paid: true };

const sent = JSON.stringify(order);
console.log("Sent over the network:", sent);

const received = JSON.parse(sent);
console.log("Items received:", received.items.length);
```

Expected output:

```text
Sent over the network: {"id":5012,"items":["pen","notebook"],"paid":true}
Items received: 2
```

`fetch()` sends and receives JSON exactly like this. The **Fetch API** lesson shows that step.

### JSON vs JavaScript Objects

<div className="tscroll">

| | JavaScript object | JSON |
|---|---|---|
| What it is | a value in memory | a piece of text |
| Keys | quotes optional | double quotes required |
| Strings | `'`, `"` or `` ` `` | double quotes only |
| Trailing comma | allowed | not allowed |
| Comments, functions, `undefined` | allowed | not allowed |

</div>

```js runnable title="The same data as an object and as JSON"
const customer = { name: "Ravi", active: true };
const customerJson = '{"name":"Ravi","active":true}';

console.log(customer.name);
console.log(customerJson.name);
console.log(JSON.parse(customerJson).name);
```

Expected output:

```text
Ravi
undefined
Ravi
```

## JSON Structure

### Key-Value Pairs

A key in double quotes, a colon, a value. Values can be a string, number, boolean, `null`, object or array.

```js runnable title="Every key in JSON is a double-quoted string"
const json = '{"title": "Desk Lamp", "price": 1299, "inStock": true, "discount": null}';

const product = JSON.parse(json);
console.log(product.title, product.price, product.inStock, product.discount);
```

Expected output:

```text
Desk Lamp 1299 true null
```

### Objects in JSON

Pairs inside `{ }`. Parsing gives a normal JavaScript object.

```js runnable title="A JSON object becomes a JavaScript object"
const json = '{"id": 101, "name": "Meera", "city": "Kochi"}';

const user = JSON.parse(json);
console.log(Object.keys(user));
console.log(user.city);
```

Expected output:

```text
[
  "id",
  "name",
  "city"
]
Kochi
```

### Arrays in JSON

Values inside `[ ]`. Parsing gives a real array.

```js runnable title="A JSON array becomes a JavaScript array"
const json = '["Chennai", "Pune", "Kochi"]';

const cities = JSON.parse(json);
console.log(Array.isArray(cities));
console.log(cities.length, cities[0]);
```

Expected output:

```text
true
3 Chennai
```

### Nested JSON

Objects and arrays inside each other, like an order with a customer and items. Read it with dots and brackets.

```js runnable title="An order with a nested customer and a list of items"
const json = `{
  "id": 5012,
  "customer": { "name": "Asha", "city": "Chennai" },
  "items": [
    { "sku": "PEN-01", "qty": 3 },
    { "sku": "NTB-02", "qty": 1 }
  ]
}`;

const order = JSON.parse(json);
console.log(order.customer.name);
console.log(order.items[1].sku);
console.log(order.items.length);
```

Expected output:

```text
Asha
NTB-02
2
```

## Converting Data

### JSON.stringify()

Turns a value into a JSON string. Strings keep their double quotes inside the text.

```js runnable title="stringify works on many kinds of value"
console.log(JSON.stringify(42));
console.log(JSON.stringify("Asha"));
console.log(JSON.stringify(true));
console.log(JSON.stringify(null));
console.log(JSON.stringify(["pen", "notebook"]));
```

Expected output:

```text
42
"Asha"
true
null
["pen","notebook"]
```

### Converting Objects to JSON

The usual job: a whole object, nested parts included, becomes one line of text.

```js runnable title="An object becomes one line of JSON text"
const cart = {
  owner: "Meera",
  items: [
    { name: "Pen", price: 20 },
    { name: "Notebook", price: 65 },
  ],
  total: 85,
};

const json = JSON.stringify(cart);
console.log(json);
console.log(typeof json);
```

Expected output:

```text
{"owner":"Meera","items":[{"name":"Pen","price":20},{"name":"Notebook","price":65}],"total":85}
string
```

### Formatting JSON Output (indentation)

`JSON.stringify(value, null, 2)` adds line breaks and 2-space indentation. The `null` means "no replacer".

```js runnable title="The third argument adds line breaks and indentation"
const cart = { owner: "Meera", items: ["Pen", "Notebook"], total: 85 };

console.log(JSON.stringify(cart, null, 2));
```

Expected output:

```text
{
  "owner": "Meera",
  "items": [
    "Pen",
    "Notebook"
  ],
  "total": 85
}
```

## Parsing JSON

### JSON.parse()

Turns JSON text into the value it describes: `"42"` becomes the number `42`.

```js runnable title="parse turns JSON text into values"
console.log(JSON.parse("42") + 8);
console.log(JSON.parse("true"));
console.log(JSON.parse('"Asha"').toUpperCase());
console.log(JSON.parse("[10, 20, 30]")[2]);
```

Expected output:

```text
50
true
ASHA
30
```

### Converting JSON to JavaScript Objects

The parsed object is new and ordinary: change it freely. The original text does not change.

```js runnable title="A parsed object is an ordinary object"
const json = '{"name":"Ravi","points":40,"tags":["gold","early"]}';

const member = JSON.parse(json);
member.points = member.points + 10;
member.tags.push("loyal");

console.log(member);
console.log(json);
```

Expected output:

```text
{
  "name": "Ravi",
  "points": 50,
  "tags": [
    "gold",
    "early",
    "loyal"
  ]
}
{"name":"Ravi","points":40,"tags":["gold","early"]}
```

`JSON.parse(JSON.stringify(obj))` makes a deep copy of plain data. The next section shows what gets lost.

## What JSON Cannot Carry

JSON has only six value types: string, number, boolean, `null`, object, array. Anything else changes or disappears.

### Date becomes a string

A `Date` becomes ISO text, and parsing leaves it as text.

```js runnable title="A Date goes in, and a string comes out"
const booking = { guest: "Asha", checkIn: new Date("2026-10-05T14:00:00.000Z") };

const json = JSON.stringify(booking);
console.log(json);

const back = JSON.parse(json);
console.log(typeof back.checkIn);
console.log(back.checkIn instanceof Date);
```

Expected output:

```text
{"guest":"Asha","checkIn":"2026-10-05T14:00:00.000Z"}
string
false
```

### undefined and functions are dropped

In an object, keys holding `undefined` or a function vanish.

```js runnable title="undefined and a method vanish from the text"
const profile = {
  name: "Kiran",
  nickname: undefined,
  greet() {
    return "Hello";
  },
  city: "Pune",
};

const json = JSON.stringify(profile);
console.log(json);
console.log(Object.keys(JSON.parse(json)));
```

Expected output:

```text
{"name":"Kiran","city":"Pune"}
[
  "name",
  "city"
]
```

### NaN and Infinity become null

```js runnable title="Special numbers turn into null"
const stats = { average: 0 / 0, growth: 1 / 0, visits: 1200 };

console.log(stats.average, stats.growth);
console.log(JSON.stringify(stats));
```

Expected output:

```text
NaN Infinity
{"average":null,"growth":null,"visits":1200}
```

### Map and Set become `{}`

Convert first: `Object.fromEntries(map)` and `[...set]`.

```js runnable title="A Map and a Set lose all their contents"
const stock = new Map([["pens", 120], ["notebooks", 45]]);
const tags = new Set(["sale", "new"]);

console.log(JSON.stringify({ stock, tags }));
console.log(JSON.stringify({ stock: Object.fromEntries(stock), tags: [...tags] }));
```

Expected output:

```text
{"stock":{},"tags":{}}
{"stock":{"pens":120,"notebooks":45},"tags":["sale","new"]}
```

### Same values in arrays behave differently

Inside an array, `undefined` and functions become `null`, so later items keep their positions.

```js runnable title="The same values, in an object and in an array"
const inObject = { first: "pen", second: undefined, third: () => "hi" };
const inArray = ["pen", undefined, () => "hi", NaN];

console.log(JSON.stringify(inObject));
console.log(JSON.stringify(inArray));
```

Expected output:

```text
{"first":"pen"}
["pen",null,null,null]
```

None of these changes throws an error. They happen silently. Check these rules when data looks wrong after a round trip.

## Replacer, Reviver and toJSON

| Hook | Where | Job |
|---|---|---|
| Replacer | 2nd argument of `stringify` | Choose what to write |
| Reviver | 2nd argument of `parse` | Fix values while reading |
| `toJSON()` | A method on the object | The object picks its own JSON form |

### Replacer: pick what to include

An array lists the keys to keep. A function sees each key and value; returning `undefined` drops the key.

```js runnable title="Two ways to leave fields out"
const user = { name: "Meera", email: "meera@example.com", password: "s3cret", city: "Kochi" };

console.log(JSON.stringify(user, ["name", "city"]));

const hidePassword = (key, value) => (key === "password" ? undefined : value);
console.log(JSON.stringify(user, hidePassword));

const maskEmail = (key, value) => (key === "email" ? "[hidden]" : value);
console.log(JSON.stringify(user, maskEmail));
```

Expected output:

```text
{"name":"Meera","city":"Kochi"}
{"name":"Meera","email":"meera@example.com","city":"Kochi"}
{"name":"Meera","email":"[hidden]","password":"s3cret","city":"Kochi"}
```

### Reviver: fix values while parsing (dates)

The reviver sees each key and value; what it returns is used. Turn date strings back into `Date`s.

```js runnable title="Turning a date string back into a Date"
const json = '{"guest":"Asha","checkIn":"2026-10-05T14:00:00.000Z","nights":3}';

const plain = JSON.parse(json);
console.log(plain.checkIn instanceof Date);

const booking = JSON.parse(json, (key, value) => (key === "checkIn" ? new Date(value) : value));
console.log(booking.checkIn instanceof Date);
console.log(booking.checkIn.getUTCDate());
console.log(booking.nights);
```

Expected output:

```text
false
true
5
3
```

### toJSON: object chooses its own JSON

If an object has `toJSON()`, `stringify` writes its result instead. `Date` has one built in.

```js runnable title="An object that decides its own JSON form"
const price = {
  amountInPaise: 129900,
  currency: "INR",
  toJSON() {
    return { amount: this.amountInPaise / 100, currency: this.currency };
  },
};

console.log(JSON.stringify({ item: "Desk Lamp", price }));

const when = new Date("2026-10-05T14:00:00.000Z");
console.log(when.toJSON());
```

Expected output:

```text
{"item":"Desk Lamp","price":{"amount":1299,"currency":"INR"}}
2026-10-05T14:00:00.000Z
```

Replacer: the sender decides. `toJSON`: the object always decides. Reviver: rebuild special values on the way in.

## Common JSON Errors

`JSON.parse()` is strict: any broken rule throws a `SyntaxError`. `stringify` throws for loops and BigInts.

### Invalid JSON Syntax

Single quotes are not valid JSON.

```js runnable expect-error title="Single quotes are not valid JSON"
const json = "{'name': 'Asha'}";

JSON.parse(json);
```

### Missing Quotes Around Keys

Every key needs double quotes.

```js runnable expect-error title="A key without quotes breaks the parse"
const json = '{name: "Asha", city: "Chennai"}';

JSON.parse(json);
```

### Trailing Commas

No comma after the last item.

```js runnable expect-error title="A comma after the last item is not allowed"
const json = '{"name": "Asha", "city": "Chennai",}';

JSON.parse(json);
```

### Circular Reference Error

An object that contains itself (through another object) can never be written as text.

```js runnable expect-error title="An object that points to itself cannot become text"
const employee = { name: "Ravi" };
const team = { name: "Support", lead: employee };
employee.team = team;

JSON.stringify(team);
```

The error is a `TypeError`:

```text
Converting circular structure to JSON
    --> starting at object with constructor 'Object'
    |     property 'lead' -> object with constructor 'Object'
    --- property 'team' closes the circle
```

### BigInt Error

JSON has no BigInt. Convert it with `.toString()` first, and back with `BigInt()`.

```js runnable expect-error title="A BigInt value cannot be written as JSON"
const account = { holder: "Meera", balance: 9007199254740993n };

JSON.stringify(account);
```

### Error message shows the position

The message gives the **position** (characters from the start, counting from 0) where parsing stopped. Look just before it.

```js runnable title="Using the position in the message to find the mistake"
const json = '{"sku": "PEN-01", "qty": 3,}';

try {
  JSON.parse(json);
} catch (error) {
  console.log(error.name);
  console.log(error.message);
  console.log(json.slice(24));
}
```

Expected output:

```text
SyntaxError
Expected double-quoted property name in JSON at position 27 (line 1 column 28)
 3,}
```

### Parsing safely with try/catch

JSON from a network, file or user is **untrusted**. Wrap `JSON.parse()` in `try`/`catch` and use a fallback.

```js runnable title="A parse that never crashes the program"
function safeParse(text, fallback) {
  try {
    return JSON.parse(text);
  } catch (error) {
    console.log("Could not parse:", error.name);
    return fallback;
  }
}

console.log(safeParse('{"theme":"dark"}', {}));
console.log(safeParse("{theme: dark}", { theme: "light" }));
console.log(safeParse("", { theme: "light" }));
```

Expected output:

```text
{
  "theme": "dark"
}
Could not parse: SyntaxError
{
  "theme": "light"
}
Could not parse: SyntaxError
{
  "theme": "light"
}
```

### JSON.parse("null") is valid null

`"null"` parses to `null` successfully. Only `try`/`catch` tells a real failure apart.

```js runnable title="null is a real answer, not a failure"
console.log(JSON.parse("null"));

const saved = JSON.parse("null");
console.log(saved ?? "fallback used");

let parsedOk = true;
try {
  JSON.parse("not json");
} catch {
  parsedOk = false;
}
console.log(parsedOk);
```

Expected output:

```text
null
fallback used
false
```

`JSON.parse()` never returns `null` for bad text. It throws. `if (!result)` does not protect you.

## JSON on a Web Page

Save the cart as JSON text, show it, then parse it back with a safe parser. Edit the text in the box and press the button.

```js runnable preview="notices" title="Saving and loading a cart as JSON"
const box = document.querySelector("#notices");
const cart = { owner: "Asha", items: [{ name: "Notebook", price: 60, qty: 2 }], savedAt: new Date("2026-09-01T12:00:00Z") };

const area = document.createElement("textarea");
area.rows = 7;
area.value = JSON.stringify(cart, null, 2);
const load = document.createElement("button");
load.textContent = "Load from JSON";
const result = document.createElement("p");
box.append(area, load, result);

function safeParse(text) {
  try {
    return JSON.parse(text, (key, value) => (key === "savedAt" ? new Date(value) : value));
  } catch (error) {
    return error;
  }
}

load.addEventListener("click", () => {
  const data = safeParse(area.value);
  if (data instanceof Error) {
    result.textContent = "Broken JSON: " + data.message;
  } else {
    const total = data.items.reduce((sum, item) => sum + item.price * item.qty, 0);
    result.textContent = `${data.owner}'s cart: ₹${total}, saved on ${data.savedAt.toISOString().slice(0, 10)}`;
  }
  console.log(result.textContent);
});
```

Press the button, then add a comma after the last `}` and press it again. You get the real `SyntaxError` message.

**Easy way to remember:** **stringify** = make a **string** (to send). **parse** = read the text back (to use).

## TL;DR

- JSON is text. `stringify` makes it; `parse` reads it.
- Keys and strings need double quotes; no trailing commas or comments.
- Dates become strings; `undefined`/functions vanish; `NaN` becomes `null`; Maps and Sets become `{}`.
- Replacer, reviver and `toJSON` control the conversion.
- Wrap `JSON.parse()` in `try`/`catch`; read the position in the error.

## Try this

In **Replacer: pick what to include**, change the array to `["name", "email", "phone"]`. You get `{"name":"Meera","email":"meera@example.com"}`: missing keys are just skipped.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `data.name` on received text | It is already an object | It is a string; parse it | `undefined` |
| Using date methods after loading | Dates survive JSON | They come back as strings | `getUTCDate is not a function` |
| Saving `undefined` values | They are kept | They are dropped; use `null` | Fields go missing |
| Saving a Map or Set | JSON sees their contents | They become `{}` | Data is lost |
| `{'name': 'Asha',}` | JSON is like JS | Double quotes, no trailing comma | `SyntaxError` |
| `JSON.parse()` with no `try` | Bad text gives `null` | It throws | The program crashes |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `JSON.stringify(value)` | turn a value into compact JSON text |
| `JSON.stringify(value, null, 2)` | JSON text indented by two spaces |
| `JSON.stringify(value, ["a", "b"])` | include only the listed keys |
| `JSON.stringify(value, (key, value) => …)` | a replacer function, where returning `undefined` drops the key |
| `JSON.parse(text)` | turn JSON text back into a value, or throw on bad text |
| `JSON.parse(text, (key, value) => …)` | a reviver that can rebuild values such as dates |
| `toJSON() { … }` | a method that lets an object choose its own JSON |
| `Object.fromEntries(map)` / `[...set]` | make a Map or Set safe to stringify |
| `try { JSON.parse(text) } catch { … }` | parse untrusted text without crashing |

</div>

## Exercises

## What to Remember

- JSON is how data travels: text in, text out.
- Know what JSON cannot carry.
- Always parse untrusted text inside `try`/`catch`.

Next: **Error and Exception Handling**. The kinds of errors JavaScript raises, and how `try`, `catch`, `finally` and `throw` handle them.
