JavaScript JSON.parse(): Decode and Validate
Quick answer
JSON.parse converts valid JSON text into JavaScript data. Invalid JSON raises SyntaxError; successful parsing alone does not validate the application schema.
How it works
Use JSON.parse(text) inside a narrowly scoped try/catch when input may be invalid. Check types, required own properties and allowed ranges after parsing. Duplicate object member names resolve to the last value in JavaScript JSON.parse; do not rely on duplicates for interoperable data. Large integers parsed as Number can lose precision; transport identifiers as strings.
const o=JSON.parse('{"count":3,"count":5}'); console.log(o.count);Expected output in Node.js:
5The later member replaces the earlier value.
const data=JSON.parse("null"); console.log(data===null, typeof data);Expected output in Node.js:
true objectValid JSON may produce null, not a record.
Common mistakes
Do not assume valid JSON is a valid user profile. The input may be null or an array instead of an object.
Practice
Parse a string and return the nonnegative safe integer property count when present, otherwise -1.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript JSON.parse(): Decode and Validate — Knowledge Check
Apply the taught concept and predict the output.
Which error class is expected for invalid JSON text?
What must happen after parsing an untrusted JSON configuration?
How should an exact large identifier be represented for JSON exchange?
What is the exact console output in JavaScript JSON.parse(): Decode and Validate example 1?
const o=JSON.parse('{"count":3,"count":5}'); console.log(o.count);What is the exact console output in JavaScript JSON.parse(): Decode and Validate example 2?
const data=JSON.parse("null"); console.log(data===null, typeof data);