Loading lessons...
JSON Parse
JSON Parse
JSON.parse() converts a JSON string into a JavaScript object.
The problem
When a server sends data, it arrives as text. To use it in your code, you must parse it.
const jsonText = '{"name": "Ada", "age": 36}';
const obj = JSON.parse(jsonText);
obj.name; // "Ada"
obj.age; // 36
Why parse?
Before parsing, the data is just a string. After parsing, it becomes a real object you can read and modify.
Parsing arrays
const jsonArray = '[1, 2, 3]';
const arr = JSON.parse(jsonArray);
arr[0]; // 1
Handling errors
If the text is not valid JSON, parse throws an error. Wrap it in try/catch:
try {
JSON.parse("not json");
} catch (err) {
console.log("Bad JSON");
}
TL;DR
- JSON.parse turns JSON text into an object.
- Data from servers is text, so parse it first.
- Invalid JSON throws an error.
- Use try/catch to handle bad input.