JSON in JavaScript

Why should you care about JSON?

JSON is a widely used text format for exchanging and storing structured data in web applications. If you use APIs, local storage, or backend integration, you will work with JSON frequently.

JSON stands for JavaScript Object Notation. It is a lightweight text format used to store and transfer structured data between systems such as a browser and a server.

JSON provides a standard text format that different systems can use to exchange structured data. Although it was inspired by JavaScript, JSON is a language-independent data format supported by many programming languages, including JavaScript, Python, Java, PHP, and Go.

Every time you use a web app that loads data - a weather widget, a product listing, a user profile - there is a very good chance JSON is involved behind the scenes.

javascript

// A JSON string - it is text
const jsonString = '{"product": "Laptop", "price": 999.99, "inStock": true}';

// Parse it into a real JavaScript object
const order = JSON.parse(jsonString);
console.log(order.product); // Laptop
console.log(order.price);   // 999.99

JSON looks a lot like a JavaScript object, but it is not the same thing. JSON used for transfer or storage is represented as JSON text. A JavaScript object is a live, in-memory value. You convert between them using JSON.parse() and JSON.stringify().

JSON has very strict formatting rules. One small mistake - an unquoted key, a trailing comma, a single quote instead of double - and it will not parse. The browser will throw a syntax error.

Here are the rules you must follow:

  • Keys must always be in double quotes
  • String values must also use double quotes
  • No trailing commas after the last property
  • No comments allowed inside JSON
  • No undefined, no functions, no Date objects as values

javascript

// Valid JSON
{
  "product": "Laptop",
  "price": 999.99,
  "active": true,
  "address": null
}

// Invalid JSON - key not quoted, trailing comma, single quotes
{
  product: 'Laptop',
  price: 999.99,
}

A good habit is to validate your JSON using a free tool like jsonlint.com whenever you are writing it by hand. It catches issues immediately.

When JSON is used for transfer or storage, it is represented as JSON text. JavaScript code normally parses that text into JavaScript values before working with the data.

Sharp comparison between JSON and JavaScript objects.
Question JSON JavaScript object
What is it? Text that follows a strict data format. A live value held in memory.
Can you access a property? No. Parse it first. Yes: order.product.
Keys and strings Must use double quotes. Keys may be unquoted when valid identifiers; strings may use single or double quotes.
Functions and undefined Not valid JSON values. Allowed in an object, though serialization may omit them.
How does it cross a boundary? Send or store the string. Use JSON.stringify() to create JSON text.

javascript

const order = {
  product: "Laptop",
  getTotal() {
    return 999.99;
  }
};

console.log(order.product); // works: this is a JavaScript object

const jsonText = JSON.stringify(order);
console.log(typeof jsonText); // "string"
// jsonText.product would be undefined: text has no object properties

const parsedOrder = JSON.parse(jsonText);
console.log(parsedOrder.product); // works again: object restored from JSON
Boundary rule: parse JSON text when it enters your JavaScript program; stringify JavaScript values when they leave for an API, file, or storage.

JSON supports exactly six value types. Unlike JavaScript, you cannot use functions, undefined, Symbol, or native Date objects as JSON values. JSON numbers must also be finite, so NaN, Infinity, and -Infinity are not valid JSON values.

  • String - must use double quotes: "hello"
  • Number - integer or decimal: 42, 3.14
  • Boolean - true or false
  • Null - represents empty or unknown: null
  • Array - an ordered list: [1, 2, 3]
  • Object - key-value pairs: {"key": "value"}

javascript

// All six JSON data types
const json = `{
  "product": "Laptop",
  "score": 98.5,
  "passed": true,
  "notes": null,
  "tags": ["beginner", "js"],
  "profile": { "city": "Delhi" }
}`;

const data = JSON.parse(json);
console.log(typeof data.name);         // string
console.log(typeof data.score);        // number
console.log(typeof data.passed);       // boolean
console.log(data.notes);               // null
console.log(Array.isArray(data.tags)); // true
console.log(typeof data.profile);      // object
Watch out: JSON does not support JavaScript's Date object. If you stringify a Date, it becomes an ISO string like "2026-04-06T10:00:00.000Z". You have to parse it back into a Date manually.

JSON.parse() converts a JSON string into a JavaScript value, such as an object or array. You use it when JSON text comes from a server, a file, or storage; some web APIs provide a convenience method such as response.json() that parses the response for you.

javascript

const jsonString = '{"product": "Laptop", "price": 999.99}';
const order = JSON.parse(jsonString);

console.log(order.product); // Laptop
console.log(order.price);   // 999.99
console.log(typeof order);  // object

JSON.parse() throws a SyntaxError when the input is invalid. If invalid JSON is possible, handle the error with try/catch:

javascript

try {
  const data = JSON.parse("this is not valid json");
} catch (e) {
  console.error("Parsing failed:", e.message);
  // Parsing failed: Unexpected token 'h', "this is "... is not valid JSON
}

JSON.parse() also accepts an optional reviver function as a second argument. This lets you transform values during parsing. For example, turning a date string back into a Date object:

javascript

const jsonStr = '{"product": "Laptop", "ordered": "2026-01-15T00:00:00.000Z"}';

const order = JSON.parse(jsonStr, (key, value) => {
  if (key === "ordered") return new Date(value);
  return value;
});

console.log(order.product);              // Laptop
console.log(order.ordered instanceof Date); // true

JSON.stringify() does the opposite of JSON.parse() - it converts a JavaScript object into a JSON string. You use this when you want to send data to a server or save it to localStorage.

javascript

const order = { product: "Laptop", price: 999.99 };
const jsonString = JSON.stringify(order);

console.log(jsonString);        // '{"product":"Laptop","price":999.99}'
console.log(typeof jsonString); // string

The third argument adds indentation, which makes the output easier to read:

javascript

const order = { product: "Laptop", price: 999.99 };
const pretty = JSON.stringify(order, null, 2);
console.log(pretty);
// {
//   "product": "Laptop",
//   "price": 999.99
// }

Functions and undefined values are handled differently depending on their position: object properties are omitted, while array entries become null. If the top-level value itself is undefined or a function, JSON.stringify() returns undefined. Circular references still throw a TypeError.

javascript

const obj = {
  product: "Laptop",
  getTotal: function() { return 999.99; },
  score: undefined
};

console.log(JSON.stringify(obj)); // '{"product":"Laptop"}'
// getTotal and score are silently dropped

JSON serialization is not a general deep-cloning tool: it loses unsupported values and converts types such as Date to strings. Use it when you need JSON text, and choose a different cloning approach when preserving JavaScript types matters.

The second argument is a replacer function or an array of property names. When an array is used, only the listed properties are included. This can exclude fields you do not want to serialize, but it should not be treated as complete security:

javascript

const order = { product: "Laptop", price: 999.99, couponCode: "SAVE20" };

// Only include product and price - keep couponCode out
const safe = JSON.stringify(order, ["product", "price"]);
console.log(safe); // '{"product":"Laptop","price":999.99}'

JSON objects can contain other objects inside them. This is called nesting. You use it to represent structured data - like a user who has an address, which has a city and a zip code.

javascript

const jsonStr = `{
  "product": "Laptop",
  "shipping": {
    "city": "Delhi",
    "zip": "110001",
    "country": "India"
  }
}`;

const order = JSON.parse(jsonStr);

console.log(order.shipping.city);    // Delhi
console.log(order.shipping.zip);     // 110001
console.log(order.shipping.country); // India

Very deeply nested structures can become harder to read and maintain, so consider whether the data structure can be simplified when nesting becomes excessive.

javascript

const data = {
  "store": {
    "catalog": {
      "item": {
        "sku": "LPT-1001"
      }
    }
  }
};

// Access with dot notation
console.log(data.store.catalog.item.sku); // LPT-1001

// Use optional chaining to avoid errors when a level is missing
console.log(data.store?.catalog?.item?.price); // undefined - no crash

A JSON value can be an array. Arrays in JSON work exactly like JavaScript arrays - they hold an ordered list of values and you access items using their index.

javascript

const jsonStr = '{"items": ["Laptop", "Mouse", "Keyboard"]}';
const data = JSON.parse(jsonStr);

console.log(data.items[0]);     // Laptop
console.log(data.items.length); // 3

Arrays can also contain objects. This is the most common pattern you will see when fetching data from an API - a list of user objects, product objects, or post objects:

javascript

const jsonStr = `{
  "products": [
    { "id": 1, "product": "Laptop",   "available": true },
    { "id": 2, "product": "Monitor",  "available": false },
    { "id": 3, "product": "Keyboard", "available": true }
  ]
}`;

const result = JSON.parse(jsonStr);

console.log(result.products[1].product);   // Monitor
console.log(result.products[2].available); // true

// Loop through the array
result.products.forEach(item => {
  console.log(item.product, item.available ? "available" : "unavailable");
});
// Laptop available
// Monitor unavailable
// Keyboard available

You can also have a top-level JSON array - the entire JSON is just an array, not wrapped in an object:

javascript

const jsonStr = '[1, 2, 3, 4, 5]';
const numbers = JSON.parse(jsonStr);
console.log(numbers[0]);      // 1
console.log(numbers.length);  // 5

JSON and JavaScript objects look almost identical, which causes a lot of confusion. But they are not the same thing. Here are the key differences:

  • Keys: In JSON, keys must be in double quotes. In a JS object, keys can be unquoted.
  • Values: JSON supports only 6 types. A JS object can hold functions, undefined, Symbols, and more.
  • Functions: Not allowed in JSON. Silently dropped by JSON.stringify().
  • undefined: Not valid in JSON. Silently dropped by JSON.stringify().
  • Type: JSON used for transfer or storage is represented as text. A JS object is a live data structure in memory.
  • Comments: Not allowed in JSON. Fine in JavaScript code.

javascript

// JavaScript Object - flexible, lives in memory
const order = {
  product: "Laptop",              // unquoted key - valid in JS
  price: 999.99,
  getTotal() { return 999.99; }   // function - not allowed in JSON
};

// JSON - always a string, strict format
const json = '{"product": "Laptop", "price": 999.99}';

// Convert between them
const obj = JSON.parse(json);     // JSON string => JS object
const str = JSON.stringify(order); // JS object => JSON string

console.log(str); // '{"product":"Laptop","price":999.99}' - getTotal() is silently dropped
Quick rule: When JavaScript sends or stores data as JSON, it first serializes the data into JSON text. When JavaScript receives JSON text, it can parse it into JavaScript values before working with the data.
  • JSON (JavaScript Object Notation) is a text format for storing and transferring data. It works across almost every programming language.
  • JSON syntax rules: Keys must be in double quotes. No trailing commas, no comments, no functions, no undefined.
  • JSON data types: string, number, boolean, null, array, object - that is all. No functions or Date objects.
  • JSON.parse(): Converts JSON text into a JavaScript value. Throws a SyntaxError if the input is invalid; use try/catch when invalid input is possible.
  • JSON.stringify(): Converts a JavaScript value into JSON text. Functions and undefined are omitted from object properties and become null in arrays. Use the replacer and space arguments to control output.
  • Nested JSON: Objects can contain other objects. Access nested values with dot notation. Use optional chaining to avoid crashes on missing levels.
  • JSON arrays: Arrays can hold strings, numbers, or full objects. Very common when fetching a list of items from an API.
  • JSON vs object: JSON used for transfer or storage is represented as text. A JS object is live in-memory data. JSON keys must be in double quotes; JS object keys do not need quotes.
What's next? Head over to the Regular Expressions tutorial to learn how to find and match patterns in text.

Reviewed by

SimplyJavaScript Editorial Team

Technical editors and JavaScript educators with hands-on experience building frontend projects, writing learning material, and reviewing tutorials for clarity, accuracy, and beginner-friendly guidance.