Fixed: "JWT Claims Set must be a top-level JSON object" in jose for a PyJWT Token
A Node.js service rejected a JSON Web Token (JWT) from a Python service with JWTInvalid: JWT Claims Set must be a top-level JSON object. The Python service had put float("nan") in a claim, and PyJWT wrote it into the payload as NaN, which isn't JSON. Sending null instead, and making PyJWT refuse such values, fixed it.
What I Was Doing
I was checking which Python values PyJWT can put in a custom claim, for the JWT course's Custom Claims tutorial. A claim's value has to be something JSON can hold, and PyJWT stopped with a TypeError for a datetime or a set. A float("nan") gave no error at all.
To see what another service makes of such a token, I wrote two small programs in one folder: issue.py, a Python service that creates a token with PyJWT 2.15.1, and verify.mjs, a Node.js service that verifies it with jose 6.2.19. The Python service marks a score that doesn't exist yet with float("nan").
This sets up the folder with both libraries:
uv init --no-package demo
cd demo
uv add pyjwt
npm init -y
npm install jose
uv init --no-package demo creates a Python project folder named demo, and uv add pyjwt adds PyJWT to it. npm init -y writes a package.json in the same folder, and npm install jose adds jose.
This is issue.py:
import base64
import jwt
# The key both services share: 32 random bytes, written as base64.
# It's in the code only for this example; a real service loads it from its configuration.
key = base64.b64decode("C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64=")
score = float("nan") # Ada has no score yet
token = jwt.encode({"sub": "ada", "score": score}, key, algorithm="HS256")
print(token)
And this is verify.mjs, which reads the token from token.txt and verifies it with the same key:
import { readFileSync } from 'node:fs';
import { jwtVerify } from 'jose';
// The same key the Python service signs with.
const key = Uint8Array.fromBase64('C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64=');
const token = readFileSync('token.txt', 'utf8').trim();
const { payload } = await jwtVerify(token, key);
console.log(payload);
Then I ran the Python service, saved the token it printed in token.txt, and ran the Node.js service:
uv run issue.py > token.txt
node verify.mjs
> token.txt sends what issue.py prints into the file token.txt. The commands are the same in zsh, bash and PowerShell 7.
What I Expected
One of two things: PyJWT stopping with an error, as it does for a datetime (TypeError: Object of type datetime is not JSON serializable), or the Node.js service verifying the token and printing its claims.
What I Got
PyJWT created the token without a word. jose refused it:
file:///Users/Shared/you/demo/node_modules/jose/dist/webapi/lib/jwt_claims_set.js:64
throw new JWTInvalid("JWT Claims Set must be a top-level JSON object", { cause });
^
JWTInvalid: JWT Claims Set must be a top-level JSON object
at validateClaimsSet (file:///Users/Shared/you/demo/node_modules/jose/dist/webapi/lib/jwt_claims_set.js:64:11)
at jwtVerify (file:///Users/Shared/you/demo/node_modules/jose/dist/webapi/jwt/verify.js:8:19)
at async file:///Users/Shared/you/demo/verify.mjs:8:21 {
code: 'ERR_JWT_INVALID',
[cause]: SyntaxError: Unexpected token 'N', ..."","score":NaN}" is not valid JSON
at JSON.parse (<anonymous>)
at validateClaimsSet (file:///Users/Shared/you/demo/node_modules/jose/dist/webapi/lib/jwt_claims_set.js:62:22)
at jwtVerify (file:///Users/Shared/you/demo/node_modules/jose/dist/webapi/jwt/verify.js:8:19)
at async file:///Users/Shared/you/demo/verify.mjs:8:21
}
Node.js v26.13.1

The signature was right: both programs use the same key. The message talks about a "top-level JSON object", and the payload was a dictionary, so the message alone didn't explain it.
What I Checked
The cause line. jose attaches the error it got while reading the payload. That [cause] is a SyntaxError from JSON.parse, and it quotes the end of the payload: "score":NaN}. So the payload held the word NaN where a number should be. jose's source, in jwt_claims_set.ts, reads the payload with JSON.parse and turns any parse error into this message.
Whether NaN is JSON. It isn't. RFC 8259, the JSON standard, says: "Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted." And RFC 7519, the JWT standard, tells a verifier to check that the payload is "a completely valid JSON object conforming to RFC 7159". jose did exactly that.
Where the NaN came from. PyJWT turns the payload into text with Python's json.dumps, in _encode_payload, without changing its allow_nan setting. The Python documentation for json.dumps explains what that default does: "If allow_nan is true (the default), then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders."
Whether PyJWT notices. It doesn't: PyJWT's own jwt.decode read the same token back as {'sub': 'ada', 'score': nan}, because Python's json.loads accepts NaN too. A Python-only system never sees the problem. It shows up when another language verifies the token. float("inf") behaves the same way and becomes Infinity.
I reported it to PyJWT as issue #1275. Until PyJWT changes this, the fix below is in your own code.
Why It Happens
PyJWT writes float("nan") as NaN because Python's json.dumps does by default. NaN isn't valid JSON, so libraries that follow the JSON and JWT standards, such as jose, can't read the payload and reject the whole token.
The Fix
Two changes in issue.py. First, make PyJWT refuse values JSON can't hold, so a NaN can never leave the service unnoticed again. Second, send null for a score that doesn't exist yet.
1. A strict JSON encoder. jwt.encode takes a json_encoder argument, which the PyJWT documentation for jwt.encode describes as a "custom JSON encoder for payload and headers". This one turns allow_nan off:
class StrictJSONEncoder(json.JSONEncoder):
"""Stop with a ValueError on NaN and infinity, which JSON can't hold, instead of writing them into the token."""
def __init__(self, **kwargs):
kwargs["allow_nan"] = False
super().__init__(**kwargs)
class StrictJSONEncoder(json.JSONEncoder)makes a new encoder that does everything Python's standard JSON encoder does.json.dumpscreates the encoder withallow_nan=True, so__init__sets it toFalsebeforesuper().__init__(**kwargs)runs the normal setup.
Pass it to jwt.encode:
token = jwt.encode({"sub": "ada", "score": score}, key, algorithm="HS256", json_encoder=StrictJSONEncoder)
With only this change, the same NaN now stops the Python service before any token exists:
uv run issue.py > token.txt
Traceback (most recent call last):
File "/Users/Shared/you/demo/issue.py", line 21, in <module>
token = jwt.encode({"sub": "ada", "score": score}, key, algorithm="HS256", json_encoder=StrictJSONEncoder)
File "/Users/Shared/you/demo/.venv/lib/python3.15/site-packages/jwt/api_jwt.py", line 143, in encode
json_payload = self._encode_payload(
payload,
headers=headers,
json_encoder=json_encoder,
)
File "/Users/Shared/you/demo/.venv/lib/python3.15/site-packages/jwt/api_jwt.py", line 170, in _encode_payload
return json.dumps(
~~~~~~~~~~^
payload,
^^^^^^^^
separators=(",", ":"),
^^^^^^^^^^^^^^^^^^^^^^
cls=json_encoder,
^^^^^^^^^^^^^^^^^
).encode("utf-8")
^
File "/Library/Frameworks/Python.framework/Versions/3.15/lib/python3.15/json/__init__.py", line 241, in dumps
**kw).encode(obj)
~~~~~~^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.15/lib/python3.15/json/encoder.py", line 202, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/Library/Frameworks/Python.framework/Versions/3.15/lib/python3.15/json/encoder.py", line 263, in iterencode
return _iterencode(o, 0)
ValueError: Out of range float values are not JSON compliant: nan
when serializing dict item 'score'

The error now names the problem and the claim: ValueError: Out of range float values are not JSON compliant: nan, "when serializing dict item 'score'".
2. Send null when there's no number. JSON's word for "no value" is null, which is None in Python. math.isfinite tells a real number from NaN and infinity. The Python documentation for math.isfinite: "Return True if x is neither an infinity nor a NaN, and False otherwise."
# JSON has no NaN or infinity, so send null when the score isn't a finite number.
claims = {"sub": "ada", "score": score if math.isfinite(score) else None}
score if math.isfinite(score) else None keeps the score when it's a real number and uses None otherwise.
The complete issue.py:

import base64
import json
import math
import jwt
class StrictJSONEncoder(json.JSONEncoder):
"""Stop with a ValueError on NaN and infinity, which JSON can't hold, instead of writing them into the token."""
def __init__(self, **kwargs):
kwargs["allow_nan"] = False
super().__init__(**kwargs)
# The key both services share: 32 random bytes, written as base64.
# It's in the code only for this example; a real service loads it from its configuration.
key = base64.b64decode("C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64=")
score = float("nan") # Ada has no score yet
# JSON has no NaN or infinity, so send null when the score isn't a finite number.
claims = {"sub": "ada", "score": score if math.isfinite(score) else None}
token = jwt.encode(claims, key, algorithm="HS256", json_encoder=StrictJSONEncoder)
print(token)
After the Fix
uv run issue.py > token.txt
node verify.mjs
{ sub: 'ada', score: null }

jose verified the token and printed its claims. The score arrived as null, which every JSON reader understands, and the strict encoder stops any other NaN or infinity in the payload before a token is made.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Using float("nan") to mean "no value" in a claim | PyJWT writes NaN, and other services can't read the token | Use None, which becomes null, or leave the claim out |
Setting allow_nan = False as a class attribute on the encoder | It has no effect: json.dumps passes allow_nan=True when it creates the encoder | Set it in __init__, as above |
| Testing only with PyJWT on both sides | jwt.decode reads NaN back, so the problem stays hidden | Verify a sample token with the library the other service uses |
Checking a value with value == float("nan") | Always False: NaN isn't equal to anything, itself included | math.isnan(value), or math.isfinite(value) to rule out infinity too |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
JWTInvalid: JWT Claims Set must be a top-level JSON object with a [cause] that mentions NaN or Infinity | The service that made the token wrote a value JSON doesn't allow | Find the claim named in the cause, and send null or a real number |
The same message with no [cause] | The payload is valid JSON, but a list or a string instead of an object | The service that makes the token has to put its claims in a JSON object |
ValueError: Out of range float values are not JSON compliant: nan | The strict encoder found a NaN | The line after it names the claim. Send None for it |
FAQ
Is this a bug in jose?
No. jose follows RFC 7519, which requires the payload to be valid JSON, and NaN isn't. The token is the problem, not the verifier.
Why didn't PyJWT reject NaN like it rejects a datetime?
A datetime has no JSON form at all, so json.dumps raises a TypeError. For NaN and infinity, json.dumps has a non-standard form, NaN and Infinity, which it uses unless allow_nan is False.
Do other Python values cause the same problem?
float("inf") and float("-inf") do, as Infinity and -Infinity. The strict encoder stops those too.
Do I still need the strict encoder once the score is fixed?
It's what stops the next NaN. Without it, any other float that turns into NaN in your code reaches other services as a broken token instead of an error you can see.
Conclusion
A NaN in a PyJWT claim makes a token other JWT libraries reject, because JSON has no NaN. Send None for a missing number, and pass PyJWT a JSON encoder with allow_nan off, so a NaN or an infinity stops the Python service with an error instead of breaking every service that reads its tokens.
Additional Resources
- PyJWT issue #1275, the report of this problem.
- json.dumps, on
allow_nan. - jwt.encode, in the PyJWT documentation.
- RFC 8259 section 6, on numbers in JSON.
- RFC 7519 section 7.2, on validating a JWT.
