Intermediate · 12 min
Read and write JSON
Convert between JSON text and JavaScript values, then validate the shape.
Parse JSON text
JSON.parse() reads JSON text. Valid JSON does not guarantee the shape your program expects, so check important fields before using them.
const text = '{"name":"Ada","sessions":3}';
const user = JSON.parse(text);
console.log(user.name);
console.log(user.sessions);Output
Ada 3
Serialize a value
JSON.stringify() creates JSON text. JSON does not represent functions or undefined values, so it is not a general-purpose clone for every JavaScript object.
const settings = { theme: "dark", reminders: true };
console.log(JSON.stringify(settings));Output
{"theme":"dark","reminders":true}Put it into practice
- Predict each result before running the example.
- Complete the coding task, then explain why your solution works.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Summarize JSON data
Parse text and add its numeric values. Store the result in total and display it.
Use reduce() on the parsed array with an initial total of 0.