JSON to JavaScript Object: Safe Parsing Guide
To convert JSON into a JavaScript object, use JSON.parse(). That sounds simple, but safe production code also needs parse error handling and shape validation after parsing.
Basic JSON to object conversion
A valid JSON string becomes a JavaScript value: object, array, string, number, boolean, ornull.
const raw = '{"id":42,"name":"Alice","active":true}'
const user = JSON.parse(raw)
console.log(user.name)
// AliceIf you need the reverse direction, see JavaScript object to JSON.
Always catch parse failures
Invalid JSON throws a SyntaxError. This matters for user input, localStorage, uploaded files, query strings, and third-party API responses.
function parseJsonObject(raw) {
try {
return { ok: true, value: JSON.parse(raw) }
} catch (error) {
return {
ok: false,
error: error instanceof Error ? error.message : 'Invalid JSON'
}
}
}If you are debugging a parser failure, the dedicated JSON.parse error guide covers the most common error cases.
Convert JSON to nested objects and arrays
JSON naturally supports nesting. The result is a normal JavaScript object tree that you can traverse with dot notation or array indexing.
const raw = '{"user":{"profile":{"name":"Alice"}},"roles":["admin","editor"]}'
const data = JSON.parse(raw)
console.log(data.user.profile.name)
console.log(data.roles[0])For deeper structures and optional fields, read parse nested JSON in JavaScript.
Use a reviver for special value handling
A reviver runs after parsing and lets you convert specific values, such as ISO dates, into richer JavaScript objects.
const raw = '{"createdAt":"2024-01-15T10:30:00.000Z"}'
const result = JSON.parse(raw, (key, value) => {
if (key === 'createdAt' && typeof value === 'string') {
return new Date(value)
}
return value
})Parsing is not validation
Parsed JSON can still be the wrong shape. Check required fields or validate with JSON Schema before trusting the data.
const payload = JSON.parse('{"email":123}')
if (typeof payload.email !== 'string') {
throw new Error('email must be a string')
}For reusable validation rules, see JSON Schema examples.
Validate JSON before parsing it in code
Use Jsonic's JSON Formatter to catch syntax errors and the JSON Schema Validator to verify object structure.