JavaScript JSON

JSON (JavaScript Object Notation) is a lightweight data format for storing and transporting data. It's easy for humans to read and write.

JSON Basics

JSON (JavaScript Object Notation) is a lightweight, text-based format for storing and exchanging data. Despite its name, JSON is language-independent and is used across virtually all programming languages, not just JavaScript. JSON's simplicity and human readability have made it the de facto standard for web APIs, configuration files, and data storage. It's much lighter than XML and easier to parse, which is why it replaced XML for most web API communications.

JSON.parse() is a built-in JavaScript method that converts a JSON string into a JavaScript object. When you receive data from a web API or read from localStorage, the data comes as a JSON string. JSON.parse() transforms that string into a usable JavaScript object that you can access and manipulate. If the JSON string is invalid or malformed, JSON.parse() throws a SyntaxError, so you often wrap it in a try-catch block when parsing untrusted data.

JSON.stringify() does the opposite—it converts a JavaScript object into a JSON string. This is essential when you need to send data to a server via an API, store data in localStorage (which only accepts strings), or save data to a file. JSON.stringify() accepts optional parameters: a replacer function/array to filter properties, and a space parameter to format the output with indentation for readability (pretty-printing). This makes debugging and human inspection much easier.

JSON data is structured as key/value pairs enclosed in curly braces {}. Keys must be strings enclosed in double quotes (not single quotes), followed by a colon, then the value. Multiple key/value pairs are separated by commas. This structure is similar to JavaScript object literals, but JSON is stricter—keys must always be quoted, trailing commas are not allowed, and you can't include comments or functions.

JSON values can be strings (in double quotes), numbers (integer or floating-point), booleans (true or false), null, objects (nested JSON objects), or arrays (ordered lists of values). Notably, JSON cannot contain functions, undefined, symbols, or dates (dates are converted to ISO 8601 strings). This limitation keeps JSON simple and universal across different programming languages. When you stringify an object with functions or undefined, those properties are omitted from the JSON output.

// JSON string
const jsonString = '{"name":"John","age":30,"city":"New York"}';

// Parse JSON to object
const person = JSON.parse(jsonString);
console.log(person.name); // "John"
console.log(person.age);  // 30

// Object to JSON
const obj = {
  name: "Alice",
  age: 25,
  hobbies: ["reading", "coding"]
};

const json = JSON.stringify(obj);
console.log(json);
// {"name":"Alice","age":25,"hobbies":["reading","coding"]}

// Pretty print
const prettyJson = JSON.stringify(obj, null, 2);
console.log(prettyJson);

Working with JSON

JSON is the standard format for web APIs and data exchange between client and server. When you fetch data from an API using the Fetch API or XMLHttpRequest, the response is typically JSON. Modern web development heavily relies on JSON for everything from REST APIs to GraphQL, from configuration files (package.json, tsconfig.json) to NoSQL databases like MongoDB. Understanding JSON is essential for any web developer working with external data.

The Fetch API returns responses that you convert to JSON using the .json() method: fetch(url).then(response => response.json()).then(data => ...). This method parses the response body as JSON and returns a promise that resolves to the parsed JavaScript object. Most REST APIs return JSON in their responses because it's lightweight, easy to parse, and works seamlessly with JavaScript on both the client and server (Node.js). The Content-Type header is typically set to 'application/json' for JSON responses.

localStorage and sessionStorage only store strings, so you must use JSON.stringify() to convert objects before storing them and JSON.parse() to convert them back when retrieving them. This pattern is extremely common: localStorage.setItem('user', JSON.stringify(userObject)) to save, and const user = JSON.parse(localStorage.getItem('user')) to retrieve. This allows you to persist complex data structures like arrays and objects in the browser between page reloads or sessions.

JSON has important limitations compared to JavaScript objects. It cannot contain functions, undefined values, or symbols—these are omitted during stringification. Methods on objects disappear when you stringify them. Regular expressions are converted to empty objects {}. The Map and Set data structures don't stringify properly. Understanding these limitations prevents bugs when you try to serialize complex objects with non-serializable properties.

Date objects are automatically converted to ISO 8601 strings when stringified (e.g., '2024-01-15T10:30:00.000Z'), but when you parse JSON, they remain strings and don't automatically convert back to Date objects. You need to manually convert them: new Date(jsonData.timestamp). You can use the replacer and reviver parameters in JSON.stringify() and JSON.parse() to customize how special values are serialized and deserialized, allowing you to handle dates, BigInts, or custom objects properly.

// Array to JSON
const colors = ["red", "green", "blue"];
const jsonArray = JSON.stringify(colors);
console.log(jsonArray); // ["red","green","blue"]

// Nested objects
const data = {
  user: {
    name: "John",
    age: 30
  },
  posts: [
    { id: 1, title: "First Post" },
    { id: 2, title: "Second Post" }
  ]
};

const jsonData = JSON.stringify(data);
console.log(jsonData);

// Selective stringify
const filtered = JSON.stringify(data, ["user", "name"]);
console.log(filtered); // Only includes user.name