Manipulating Data with JSON

Learn to serialize and deserialize data with JavaScript. Master `JSON.stringify()` and `JSON.parse()` to communicate with any API on the web.

Lesson ProgressStep 1 of 8
const user = {
  name: "Alex",
  isStudent: true
};
const jsonString = JSON.stringify(user);
// ""name":"Alex","isStudent":true}"
const newObj = JSON.parse(jsonString);
// JSON (Keys must be double-quoted)
{ "name": "Alex" }
0 EXP

Welcome! JSON is the universal language for data on the web. Let's see how JavaScript handles it.

// JSON (JavaScript Object Notation)

What is JSON?

JSON stands for **JavaScript Object Notation**. It's a lightweight, text-based format for exchanging data. It's the standard language that web servers and browsers use to communicate.

Even though it's based on JavaScript, it's language-independent, meaning almost every programming language (Python, Java, C#, etc.) can read and write JSON.

System Check

What does JSON stand for?

Advanced Holo-Simulations

0 EXP

Log in to unlock these advanced training modules and test your skills.


Achievements

📦
Serializer

Correctly serialize a JavaScript object into a JSON string.

📬
Deserializer

Correctly parse a JSON string back into a JavaScript object.

✍️
Syntax Pro

Prove your mastery of strict JSON syntax rules.

Mission: Serialize and Deserialize

Complete the code. First, convert the `user` object into a JSON string. Then, parse that string back into a new object. Our AI assistant will provide real-time feedback.

A.D.A. Feedback:

> System integrity looks stable. Code is valid.

Challenge: Order the Data Flow

Drag the code lines into the correct logical order to serialize and deserialize data.

const str = JSON.stringify(obj);
const obj = { "a": 1 };
console.log(newObj.a);
const newObj = JSON.parse(str);

Challenge: Complete the Syntax

Fill in the missing methods and a valid JSON string.

const obj = { id: 123 };
const str = JSON.(obj);
const dataStr = '';
const newObj = JSON.(dataStr);

Consult A.D.A.

Community Holo-Net

Peer Project Review

Submit your "Serialize and Deserialize" project for feedback from other Net-Runners.

JSON: The Lingua Franca of the Modern Web

At its heart, the internet is about communication. Browsers talk to servers, servers talk to databases, and different applications talk to each other. To do this, they need a common language, a universal format for exchanging data. For decades, that language was often XML, but today, the undisputed champion is **JSON** (JavaScript Object Notation).

JSON is a lightweight, text-based **data interchange format**. It's easy for humans to read and write, and easy for machines to parse and generate. Its syntax is a subset of JavaScript, which makes it incredibly native and simple to work with inside a browser.

The Syntax: Stricter Than It Looks

JSON's structure is built on two simple concepts: a collection of key/value pairs (an **object**) and an ordered list of values (an **array**).

This sounds just like a JavaScript object, but there are critical, strict rules you must follow:

  • Keys Must Be Double-Quoted Strings: This is the most common mistake. In a JavaScript object, { name: 'Alex' } is valid. In JSON, it **must** be {"name": "Alex"}.
  • No Trailing Commas: That extra comma after the last item in an object or array, which JavaScript allows, will cause a parse error in JSON.
  • No Comments: JSON is a data-only format. It does not support `//` or `/* */` comments.
  • Values Are Limited: A value can only be one of six types: a **string** (in double quotes), a **number**, an **object**, an **array**, a **boolean** (`true` or `false`), or **`null`**.

Types like `undefined`, `Symbol`, `Date`, or functions are **not** valid JSON types.

{
  "user": "alex_dev",
  "id": 12345,
  "isActive": true,
  "lastLogin": null,
  "permissions": ["read", "write", "admin"],
  "profile": {
    "theme": "dark",
    "notifications": {
      "email": true,
      "sms": false
    }
  }
}

Serialization: `JSON.stringify()`

To send your JavaScript object data across the network, you must first convert it into a JSON string. This process is called **serialization**. JavaScript gives us a built-in tool for this: JSON.stringify().

const user = { name: "Alex", id: 123 };
const jsonString = JSON.stringify(user);
// jsonString is now '{"name":"Alex","id":123}'

`JSON.stringify()` is powerful and has two optional arguments: a `replacer` and `space`.

  • The `replacer` Argument: This can be an **array of keys** to whitelist, or a **function** to modify values as they are stringified.
  • The `space` Argument: This is for **pretty-printing**. Passing a number (like `2`) or a string (like `'\t'`) will format the output with indentation and newlines, making it human-readable.
// Using all arguments
const data = { id: 1, user: "dev", secret: "xyz" };

// 1. Replacer as an array
const whitelisted = JSON.stringify(data, ["id", "user"]);
// '{"id":1,"user":"dev"}' (secret is gone)

// 2. Space argument for pretty-printing
const pretty = JSON.stringify(data, null, 2);
// {
//   "id": 1,
//   "user": "dev",
//   "secret": "xyz"
// }

If you try to stringify an object with `undefined`, a `function`, or a `Symbol`, those properties will be silently **omitted**.

Deserialization: `JSON.parse()`

When you receive data from an API, it arrives as a JSON string. To use it in your JavaScript code, you must convert it back into an object. This is called **deserialization** (or simply "parsing"), and we use JSON.parse().

This method is **strict**. If the string is not perfectly-formed JSON (e.g., it has a trailing comma or single-quoted keys), it will throw a `SyntaxError`. You should **always** wrap `JSON.parse()` in a `try...catch` block.

const jsonString = '{"id":123,"name":"Alex"}';

try {
  const userObject = JSON.parse(jsonString);
  console.log(userObject.name); // "Alex"
} catch (error) {
  console.error("Failed to parse JSON:", error);
}

`JSON.parse()` also has an optional second argument: a **`reviver` function**. This function is called for every key/value pair as it's parsed, allowing you to transform values on the fly. The most common use case is to convert date strings back into `Date` objects.

const data = '{"name":"event","date":"2025-10-26T10:00:00Z"}';

const obj = JSON.parse(data, (key, value) => {
  // Check if the value is a string and looks like a date
  if (key === 'date') {
    return new Date(value); // Return a Date object
  }
  return value; // Return all other values as-is
});

console.log(obj.date.getFullYear()); // 2025

Where You'll Use JSON Every Day

  • APIs: This is the big one. When you use `fetch()` to get data from a server, you'll almost always use response.json(), which is just a shortcut for parsing the response body.
  • `localStorage`: `localStorage` can only store strings. To save an object or array, you must stringify it, and parse it when you retrieve it.
  • Configuration Files: Project configuration files like package.json or .eslintrc.json are all written in JSON.
Key Takeaway: JSON is the bridge between data (as a string) and JavaScript (as an object). Master the two methods, JSON.stringify() and JSON.parse(), and their strict syntax rules, and you'll have mastered the most fundamental part of modern web communication.

JSON & Data Glossary

JSON
Stands for **JavaScript Object Notation**. A lightweight, text-based data interchange format that is easy for humans to read and for machines to parse.
Data Interchange Format
A standard for structuring data so that it can be easily passed between different applications, systems, or servers, even if they are written in different programming languages.
Serialization
The process of converting an in-memory object (like a JavaScript object) into a string or byte stream for storage or transmission.
`JSON.stringify()`
The built-in JavaScript method that **serializes** a JavaScript value (object, array, etc.) into a JSON string.
Deserialization
The process of converting serialized data (like a JSON string) back into an in-memory object that the program can use. Also known as "parsing".
`JSON.parse()`
The built-in JavaScript method that **deserializes** (parses) a JSON string, converting it back into a JavaScript value (object, array, etc.).
Key
In JSON, the "name" part of a key/value pair. It **must** be a string enclosed in **double quotes** (e.g., `"name"`).
Value (JSON)
The "data" part of a key/value pair. It can be one of six types: string, number, object, array, boolean (`true`/`false`), or `null`.
`SyntaxError`
The specific error JavaScript throws when `JSON.parse()` fails because the input string is not valid JSON (e.g., it has a trailing comma, single quotes, or comments).
Replacer
An optional function or array passed as the second argument to `JSON.stringify()` to control which properties are included or to modify their values.
Reviver
An optional function passed as the second argument to `JSON.parse()` to transform values as they are being parsed (e.g., converting date strings into `Date` objects).
`toJSON()`
A special method that can be defined on an object. If it exists, `JSON.stringify()` will call this method and use its return value as the JSON representation of that object.
Pretty-Printing
The act of formatting a JSON string with newlines and indentation to make it readable for humans, typically by using the third `space` argument in `JSON.stringify()`.
Circular Reference
A situation where an object contains a reference to itself (or an object that references it, creating a loop). `JSON.stringify()` will throw an error if it encounters a circular reference.
JSON5
A superset of JSON that allows for more human-friendly features, such as comments, trailing commas, and unquoted keys. It is often used for configuration files but is not standard JSON.

About the Author

Author's Avatar

TodoTutorial Team

Passionate developers and educators making programming accessible to everyone.

This article was written and reviewed by our team of web development experts, who have years of experience teaching JavaScript and building data-driven applications.

Verification and Updates

Last reviewed: October 2025.

We strive to keep our content accurate and up-to-date. This tutorial is based on the latest ECMAScript specifications and is periodically reviewed to reflect industry best practices.

External Resources

Found an error or have a suggestion? Contact us!