JSON in JavaScript
Serializing and parsing, with error handling.
const profile = { name: "ada", langs: ["js", "rust"], active: true };
const text = JSON.stringify(profile, null, 2);
const compact = JSON.stringify(profile);
const restored = JSON.parse(text);
function safeParse(input) {
try {
return { ok: true, value: JSON.parse(input) };
} catch (error) {
return { ok: false, error: error.message };
}
}
How it works
stringifytakes indentation as its third argument.parsethrows on malformed input.- Wrapping it returns a result object instead.
Keywords and builtins used here
JSONcatchconstfunctionreturntry
The run, in numbers
- Lines
- 13
- Characters to type
- 341
- Tokens
- 100
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 63 seconds.
Step 1 of 3 in Data formats, step 40 of 43 in Language basics.