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.
let user = { name: "Ivy", age: 27 };
let json = JSON.stringify(user);
console.log(json);{"name":"Ivy","age":27}stringify converts the object into a JSON-formatted string.
let json = '{"name":"Ivy","age":27}';
let obj = JSON.parse(json);
console.log(obj.name);Ivyparse 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.
