JSON.parse: Text to Object
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
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 spacesJSON.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.
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
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 youDates 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.
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() // 2026Choosing What to Stringify
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 keyCommon Errors
- Unexpected token ' in JSON: single quotes; JSON needs double quotes.
- Unexpected end of JSON input: the text is empty or cut off.
- Unexpected token < in JSON: the server sent HTML (often an error page) instead of JSON.
- Converting circular structure to JSON: an object refers to itself and cannot be stringified.
- Bad escaped character in JSON: a backslash in a string, often in a Windows path, is not a valid escape.
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
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.