JSON.parse: Text to Object

JavaScript
const text = '{"name": "Emily", "age": 30, "tags": ["admin", "editor"]}'
const user = JSON.parse(text)

console.log(user.name)      // "Emily"
console.log(user.tags[1])   // "editor"

JSON.stringify: Object to Text

JavaScript
const user = { name: 'Emily', city: 'London', active: true }

JSON.stringify(user)
// '{"name":"Emily","city":"London","active":true}'

JSON.stringify(user, null, 2)   // pretty printed with 2 spaces

JSON.stringify skips undefined values and functions inside objects, and turns NaN and Infinity into null.

Parse Safely with try...catch

JSON.parse throws a SyntaxError for invalid JSON, which can crash your app. Always wrap it when the text comes from a user, a file or an API.

JavaScript
function safeParse(text, fallback = null) {
  try {
    return JSON.parse(text)
  } catch (error) {
    console.warn('Invalid JSON:', error.message)
    return fallback
  }
}

safeParse('{"ok": true}')    // { ok: true }
safeParse("{'ok': true}")    // null  (single quotes are not valid JSON)

Fetching JSON from an API

JavaScript
const response = await fetch('https://api.example.com/users/1024')
if (!response.ok) throw new Error('Request failed: ' + response.status)
const user = await response.json()   // parses the JSON for you

Dates and the Reviver Function

JSON has no date type, so dates are sent as text like "2026-11-08T09:30:00.000Z". A reviver lets you turn them back into Date objects while parsing.

JavaScript
const text = '{"title": "Launch", "startsAt": "2026-11-08T09:30:00.000Z"}'

const event = JSON.parse(text, (key, value) =>
  key.endsWith('At') && typeof value === 'string' ? new Date(value) : value
)

event.startsAt.getFullYear()   // 2026

Choosing What to Stringify

JavaScript
const user = { id: 1, name: 'Emily', password: 'secret' }

JSON.stringify(user, ['id', 'name'])                       // only these keys
JSON.stringify(user, (k, v) => (k === 'password' ? undefined : v))   // hide one key

Common Errors

Paste broken JSON into the JSON Formatter to see the exact line of the error and fix common mistakes automatically, or read the full guide to Unexpected token in JSON. Using TypeScript? Read JSON in TypeScript to type the parsed value safely.

Reading and Writing JSON Files in Node.js

Node.js
import { readFile, writeFile } from 'node:fs/promises'

const config = JSON.parse(await readFile('config.json', 'utf8'))
config.debug = true
await writeFile('config.json', JSON.stringify(config, null, 2) + '\n')

The 'utf8' argument returns text instead of a buffer, and the extra newline at the end keeps editors and Git happy. More options for indentation are in How to Pretty Print JSON. If JSON.stringify throws on a looping object, seeConverting circular structure to JSON. For require, import, ENOENT and BOM errors, see how to read and write a JSON file in Node.js.

Frequently Asked Questions

What is the difference between JSON.parse and JSON.stringify?

JSON.parse turns a JSON string into a JavaScript value. JSON.stringify turns a JavaScript value into a JSON string.

How do I avoid crashes from bad JSON?

Wrap JSON.parse in try...catch, because it throws a SyntaxError when the text is not valid JSON.

Why do dates become strings?

JSON has no date type, so JSON.stringify writes dates as ISO strings. Use a reviver function in JSON.parse to turn them back into Date objects.

How do I pretty print JSON in JavaScript?

Use JSON.stringify(value, null, 2). The third argument is the number of spaces to indent.

Related Tools