NaN, Infinity, True and None in JSON: what “Unexpected token ‘N’” means and how to fix it
Updated
JSON knows three words: true, false, null. Lowercase, and that’s the whole list. NaN, Infinity, undefined, True and None belong to other languages, and a strict parser stops at their first letter.
Python and JavaScript values that are not JSON
Each value below is legal in some language and illegal in JSON. NaN and Infinity come from floating-point maths, True and None from printing a Python dict, undefined from JavaScript string building:
{"ratio": NaN, "limit": Infinity, "active": True, "parent": None, "note": undefined}JSON has null for “no value” and lowercase true and false. A number that isn’t finite has no JSON form, so it becomes null, a string, or disappears, whichever your reader expects:
{"ratio": null, "limit": "Infinity", "active": true, "parent": null}Why JSON has no NaN, Infinity or undefined (RFC 8259)
RFC 8259, section 3 lists the literal names false, null and true, requires them in lowercase and ends the discussion: “No other literal names are allowed.” Section 6 closes the other door: “Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.”
The reason is portability. A JSON number is decimal text that any language can read; NaN and Infinity are floating-point states that many languages and databases can’t store, and JSON has no type tags to carry them. undefined is JavaScript’s own idea of “no property at all”; JSON expresses that by leaving the key out.
NaN and True error messages by parser
Inputs: {"a":NaN} and {"a":True}. Each message was produced by running the parser on 2026-11-08; Firefox’s comes from the SpiderMonkey source and is printed with JSON.parse: in front and the line and column after. Infinity, None and undefined give the same messages with their own first letter.
| Parser | For NaN | For True |
|---|---|---|
| Chrome 156, Node 24–25 (V8) | Unexpected token 'N', "{"a":NaN}" is not valid JSON | Unexpected token 'T', "{"a":True}" is not valid JSON |
| Firefox (SpiderMonkey) | unexpected character | unexpected character |
| Safari 27 (JavaScriptCore) | JSON Parse error: Unexpected identifier "NaN" | JSON Parse error: Unexpected identifier "True" |
| Python 3.9–3.14 | Accepted: nan | Expecting value: line 1 column 6 (char 5) |
| Go 1.25–1.27 | invalid character 'N' looking for beginning of value | invalid character 'T' looking for beginning of value |
| Java, Jackson 2.15–2.23 | Below the table | Unrecognized token 'True': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false') |
| C#, System.Text.Json 10 | 'N' is an invalid start of a value. | 'T' is an invalid start of a value. |
| C#, Newtonsoft.Json 13 | Accepted | Unexpected character encountered while parsing value: T. Path 'a', line 1, position 5. |
| PHP 8.3 | Syntax error | Syntax error |
| Rust, serde_json 1.0 | expected value at line 1 column 6 | expected value at line 1 column 6 |
| jq 1.7.1 | Accepted, printed as null | Invalid numeric literal at line 1, column 10 |
| MySQL 8.4: JSON column | Invalid JSON text: "Invalid value." at position 5 | Invalid JSON text: "Invalid value." at position 5 |
| JSON Statham Validator | Invalid literal, line 1, column 6 | Invalid literal, line 1, column 6 |
Non-standard token 'NaN': enable `JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS` to allowWhen the whole input is one bad word, V8 skips the token and says "NaN" is not valid JSON; that family, including "[object Object]", has its own page. A minus in front changes the message: for -Infinity V8 says No number after minus sign in JSON at position 6 (line 1 column 7), Go invalid character 'I' in numeric literal, Safari JSON Parse error: Invalid number. A cut-off literal such as tru gets Go’s invalid character '}' in literal true (expecting 'e') and jq’s Invalid literal.
Note the parsers that accept NaN: Python, Newtonsoft.Json and jq. Python also accepts Infinity and -Infinity, Newtonsoft even undefined. A pipeline that works because one side is lenient breaks the day the other side is JSON.parse.
How to replace NaN and Infinity before writing JSON
Fix it where the JSON is written: turn values that aren’t finite into null (or a string, if the reader must tell NaN from “missing”). Each snippet was run; the comments show the actual output.
JavaScript: JSON.stringify already writes null
const row = { ratio: 0 / 0, limit: 1 / 0, note: undefined };
console.log(JSON.stringify(row)); // {"ratio":null,"limit":null}
const keepNames = (key, value) =>
typeof value === 'number' && !Number.isFinite(value) ? String(value) : value;
console.log(JSON.stringify(row, keepNames)); // {"ratio":"NaN","limit":"Infinity"}Python: json.dumps writes NaN unless told otherwise
import json
import math
def finite_or_none(value):
if isinstance(value, float) and not math.isfinite(value):
return None
if isinstance(value, dict):
return {k: finite_or_none(v) for k, v in value.items()}
if isinstance(value, list):
return [finite_or_none(v) for v in value]
return value
row = {"ratio": float("nan"), "ok": True, "note": None}
print(json.dumps(row)) # {"ratio": NaN, "ok": true, "note": null}
print(json.dumps(finite_or_none(row), allow_nan=False)) # {"ratio": null, "ok": true, "note": null}allow_nan=False turns the silent NaN into ValueError: Out of range float values are not JSON compliant, which is the right place to find the bug. And print(row) or str(row) is Python syntax, True and None included: send json.dumps(row) instead.
Go: a pointer that marshals as null
import "math"
type Row struct {
Ratio *float64 `json:"ratio"`
}
func finite(f float64) *float64 {
if math.IsNaN(f) || math.IsInf(f, 0) {
return nil
}
return &f
}Without it json.Marshal refuses the value outright: json: unsupported value: NaN.
Java (Jackson)
static Double finiteOrNull(double x) {
return Double.isFinite(x) ? x : null;
}By default Jackson writes NaN as the string "NaN": valid JSON, but a string where readers expect a number.
C# (System.Text.Json)
using System.Text.Json;
static double? FiniteOrNull(double x) => double.IsFinite(x) ? x : null;
Console.WriteLine(JsonSerializer.Serialize(new { ratio = FiniteOrNull(double.NaN) })); // {"ratio":null}PHP
function finite_or_null(float $x): ?float
{
return is_finite($x) ? $x : null;
}
echo json_encode(['ratio' => finite_or_null(NAN)], JSON_THROW_ON_ERROR); // {"ratio":null}Without the check, json_encode fails with error 7, Inf and NaN cannot be JSON encoded.
How to keep NaN, True and None out of JSON
- Make the writer strict.
allow_nan=Falsein Python; Go, C# and PHP already refuse. A loud error at the source beats a silentNaNthat only the next service rejects. - Decide what “not a number” means for the reader:
nullfor missing, a string such as"NaN"to keep the distinction, or no key at all. - Never print data structures into JSON. Python’s
print,str()and f-strings, JavaScript’s template literals andString(value)produce source code, not JSON. - Watch the lenient readers. If Python, Newtonsoft.Json or jq accept your data, check it once with a strict parser before you rely on it.
Check literals in the validator
Try it: open the invalid-literal sample in the Validator. The card quotes the whole word, NaN or True, and points at its first letter; for -Infinity and +NaN it points at the sign. A bare word in the place of a key is a different problem: Unquoted key.
- “undefined” is not valid JSON: when the whole input is
undefinedor[object Object]. - Invalid number:
+1,.5,01and other numbers JSON spells differently. - Single quotes: the other half of a printed Python dict.
- Big numbers in JSON: numbers that are valid but lose precision.
- All JSON errors
NaN, Infinity and None in JSON: FAQ
Can JSON contain NaN or Infinity?
No. RFC 8259 says numeric values such as Infinity and NaN are not permitted. Use null, a string, or leave the key out.
Why does Python write NaN into JSON?
json.dumps has allow_nan=True by default and writes NaN, Infinity and -Infinity. Python reads them back, JSON.parse and Go don’t. Pass allow_nan=False to get an error instead.
Is True or None valid JSON?
No. JSON literals are lowercase: true, false, null. True and None appear when a Python dict is printed with print() or str(); use json.dumps().
What does JSON.stringify do with undefined?
It drops object properties whose value is undefined, writes null for undefined in arrays, and returns undefined (not a string) for JSON.stringify(undefined). NaN and Infinity become null.