JSON parsing and validation
JSON is a text format for exchanging structured data. JSON.parse() converts valid JSON text into JavaScript values, but successful parsing does not prove that the result matches your application’s expected shape. Validate external data before using it.
Local practice: The proposed teaching runtime is Node.js 26.13.1 LTS. These original offline examples were executed on Node.js 22.16.0 (Linux x64); execution on the proposed baseline and in ByteMind is not yet verified. No npm dependencies are required. Use a fresh practice directory. Code blocks are static, not a browser-based Node runner.
Parse JSON and inspect its value
const order = JSON.parse('{"quantity":3}');console.log(order.quantity);console.log(typeof order.quantity);In the directory containing the files above, run:
node main.mjsExpected standard output:
3numberExpected exit status: 0.
How it works
An external order should contain a quantity. JSON.parse may return an object, array, string, number, boolean or null. The sample uses a try block to attempt parsing and a catch block to handle invalid JSON. It then checks that the result is a non-null non-array object and that quantity is an integer from 1 to 20. The logical AND operator stops at the first false condition, so the property access is protected by earlier checks. Number.isInteger rejects numeric strings. A well-formed JSON document can still be an invalid order.
Reject malformed or wrong-shaped orders
function validOrder(text) { let value; try { value = JSON.parse(text); } catch { return false; } return value !== null && typeof value === "object" && !Array.isArray(value) && Number.isInteger(value.quantity) && value.quantity >= 1 && value.quantity <= 20;}for (const text of ['{"quantity":3}', '{"quantity":"3"}', 'null', '{broken', '{"quantity":21}']) { console.log(validOrder(text));}In the directory containing the files above, run:
node main.mjsExpected standard output:
truefalsefalsefalsefalseExpected exit status: 0.
Common mistake
Do not treat JSON.parse() as a schema validator. Do not evaluate input as JavaScript to parse it. The example is a small validation contract, not a full production request parser; real services also enforce request size, authorization and additional fields as appropriate.
Try it yourself
Test quantities 1, 20, 0 and 21 and a JSON array containing a quantity. Explain which checks reject each invalid case. Extend the exercise to validate a required nonempty bookId string.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JSON parsing and validation — knowledge check
Check your understanding of json parsing and validation.
What can JSON.parse return for the input text `null`?
Why reject {"quantity":"3"} in the sample?
What does a successful parse prove?