JSON Errors / Python / JavaScript

NaN / Infinity is not valid JSON

How to Fix: NaN / Infinity is not valid JSON

The JSON specification only allows finite numbers. NaN, Infinity, and -Infinity are not part of the grammar - so documents containing them are invalid, and different languages handle the mismatch in confusingly different ways.

Python's json.dumps() writes NaN/Infinity by default (producing invalid JSON that other parsers reject), while JavaScript's JSON.stringify() silently converts them to null (losing information). Both directions cause cross-language bugs.

{"find": "error"}paste your JSON below

Common causes

1. Python emitting NaN into "JSON"

float("nan") in your data - common from pandas/numpy computations - serializes as the literal NaN, which JavaScript and strict parsers reject.

Invalid
{"score": NaN}    ← json.dumps output, invalid for every other parser

2. JavaScript silently nulling values

JSON.stringify({x: 0/0}) produces {"x":null} - the NaN is gone and the consumer cannot tell it from a legitimate null.

3. Division by zero and missing data upstream

Aggregations over empty sets, 1/0, or uninitialized sensor readings introduce non-finite floats that only explode later, at serialization or parse time.

How to fix it

Make Python strict and explicit
import json, math

# Fail fast instead of emitting invalid JSON:
json.dumps(data, allow_nan=False)  # raises ValueError on NaN/Infinity

# Or convert to None (null) deliberately:
def clean(x):
    return None if isinstance(x, float) and not math.isfinite(x) else x

# pandas: df.where(df.notna(), None) before .to_dict()
Preserve the distinction explicitly (both languages)
// If NaN vs null matters, encode it as a string sentinel by convention:
{"score": "NaN"}
// ...and decode it on the consuming side. Both sides must agree on the contract.

Frequently asked questions

Why does JSON exclude NaN and Infinity?

JSON is language-independent, and not all languages or databases share IEEE 754 semantics for non-finite values. The spec keeps numbers portable by allowing only finite decimal literals - anything else must be represented by convention (null, strings, or separate flags).

Why does Python accept NaN when parsing but other tools do not?

Python's json module is lenient by default in both directions (it parses NaN/Infinity too). That leniency is a Python-specific extension - the moment the data crosses to JavaScript, Go, a database, or a strict validator, it breaks. Use allow_nan=False to catch it at the source.

What should an API return for a missing numeric value?

Prefer null with documented semantics, or omit the field entirely. Avoid magic numbers like -1 or 0 that can be confused with real data, and avoid relying on NaN surviving serialization - it will not.

Last updated:

Related JSON errors

You might also need

Free and in-browser, like everything on JSON Console. Browse all tools →