JSON.parse
Learn to convert a JSON string into an object with JSON.parse.
Turning text into an object
To turn a text-format value into a JavaScript object, use the built-in parse method. Pass the text as a parameter; the method returns an object.
const text = '{"name": "Alex"}';
const user = parse(text);
// user.name === 'Alex'If the text is malformed, the method throws an error. Wrap external data in try/catch to handle this safely.
Transforming with a reviver
You can pass a reviver function as the second parameter to parse. This function is called for each key-value pair and lets you modify values.
const obj = parse(text, (key, value) => {
return typeof value === 'string' ? value.trim() : value;
});Here, all string values are trimmed automatically. A reviver is a handy way to shape data as you read it.
Exercise Turn the text into an object
Turn the text in the text variable into an object and assign it to config. Use the built-in parse method.
Show example solution
Call parse with text.
Example solution:
const config = parse(text);
Test yourself
-
What does parse('{"a": 1}') return?
parse('{"a": 1}')- A string
- An object
- A number
- It throws
Show answer
An object — Correct! Object-format text is turned into an object.
-
Access a property of the object
const user = parse(text); const name = user.____;Show answer
const user = parse(text); const name = user.name; -
What happens when malformed text is parsed?
parse('{name: "Alex"}')- Returns null
- Returns an empty object
- It throws
- Returns false
Show answer
It throws — Correct! Unquoted keys are invalid; the method throws.