JavaScript ยท Chapter 47 of 55

JavaScript JSON

JSON (JavaScript Object Notation) is a lightweight text format for representing structured data, widely used for exchanging data between a client and a server.

JavaScript provides `JSON.stringify()` to convert an object into a JSON string, and `JSON.parse()` to convert a JSON string back into a JavaScript object.

Converting to JSON

`JSON.stringify(obj)` turns a JavaScript object into a JSON-formatted string, ready for storage or network transfer.

Parsing JSON

`JSON.parse(jsonString)` turns a JSON string back into a usable JavaScript object, commonly used after fetching API data.

Example 1 (javascript)
let user = { name: "Ivy", age: 27 };
let json = JSON.stringify(user);
console.log(json);
Output
{"name":"Ivy","age":27}

stringify converts the object into a JSON-formatted string.

Example 2 (javascript)
let json = '{"name":"Ivy","age":27}';
let obj = JSON.parse(json);
console.log(obj.name);
Output
Ivy

parse converts a JSON string back into an object you can use.

Key points

  • JSON.stringify() converts a JS object into a JSON string.
  • JSON.parse() converts a JSON string into a JS object.
  • JSON keys must be double-quoted strings.
  • JSON is the standard format for APIs and config files.
๐Ÿ’ก Note: JSON cannot represent functions, undefined, or circular references โ€” those are dropped or throw errors during stringify.

๐Ÿ“ Quick Quiz

1. Which converts an object to a JSON string?

2. Which converts a JSON string to an object?

3. In JSON, keys must be: