JSON errors

JavaScript, from JSON.parse()

"undefined" is not valid JSON

JSON.parse received undefined, turned it into the text "undefined" and failed on the u. Something you expected to hold a JSON string was never set.

How each browser and language words it

Chrome, Edge and Node 20+
SyntaxError: "undefined" is not valid JSON
Older Chrome and Node 18 and below
SyntaxError: Unexpected token u in JSON at position 0
Firefox
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Paste your JSON to find the exact line

The parser was handed the word undefined, the fix is wherever that value should have come from.

Skip to editor
Explorer
Open Files

No files open

0 files open

jsoneditor.io v2

undefined
JSONUTF-8
Spaces: 2

Causes and how to fix each one

1. A property or environment variable that does not exist

JSON.parse(event.body) when the request had no body, or JSON.parse(process.env.CONFIG) when the variable isn't set, both pass undefined. Check the value exists and fail with a message that names it.

JavaScript
const raw = process.env.FEATURE_FLAGS
if (raw === undefined) {
  throw new Error('FEATURE_FLAGS is not set')
}
const flags = JSON.parse(raw)

2. Reading storage as a property

localStorage.user returns undefined for a missing key, while localStorage.getItem('user') returns null, which JSON.parse handles. Use getItem and a fallback.

3. A value saved as the string "undefined"

JSON.stringify(undefined) returns undefined, and saving that with setItem stores the text "undefined". Every later read then fails. Remove the bad entry and avoid saving undefined values.

Questions people ask

Why does JSON.parse(null) work but JSON.parse(undefined) throws?

null becomes the string "null", which is valid JSON and parses to null. undefined becomes the string "undefined", which is not a JSON value at all.

Is undefined allowed anywhere in JSON?

No. JSON has null but no undefined. JSON.stringify drops object properties whose value is undefined and writes null for undefined items in arrays.

Tools for this