JSON to JavaScript Object: Safe Parsing Guide

Last updated:

JSON.parse(jsonString) converts a JSON string to a JavaScript value in 1 synchronous call, returning 1 of 6 possible types: Object, Array, string, number, boolean, or null. It throws SyntaxError for invalid JSON — always wrap in try/catch when the input is untrusted. In TypeScript the return type is any; cast to unknown and add a Zod schema or type guard to close that 1-line safety gap. The optional 2nd argument is a reviver function that transforms each parsed value — the most common use is converting ISO 8601 strings to native Date objects. This guide covers 4 topics: the full parse pattern, reviver functions, localStorage round-trip patterns, and TypeScript-safe validation with Zod.

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)
// Alice

If 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.

Frequently asked questions

How do I convert a JSON string to a JavaScript object?

Call JSON.parse(jsonString). The result is the JavaScript equivalent of the JSON value. Wrap in try/catch for untrusted input and validate the shape before using it.

What is the difference between JSON.parse and eval()?

JSON.parse is safe and only accepts valid JSON. eval() executes arbitrary JavaScript, making it a serious security risk. Never use eval() for parsing JSON.

How do I handle null values after parsing?

Use optional chaining (data?.user?.name) and nullish coalescing (data?.name ?? 'default') to safely access properties that may benull or missing.

Can I parse JSON in a browser without a library?

Yes. JSON.parse is a built-in global available in all modern browsers and Node.js. No library or import is needed.

What is the result type of JSON.parse?

TypeScript types it as any. At runtime the type depends on the JSON: object, array, string, number, boolean, or null. Cast or validate with a library like Zod to get type safety.

How do I parse a JSON array in JavaScript?

JSON.parse handles top-level arrays: JSON.parse('[1,2,3]') returns a JavaScript array. Check with Array.isArray(result) before iterating to guard against unexpected shapes.