2

I need to write a test in Python to validate that the payload I am returning is a valid JSON.

import json
s = '{"position": NaN, "score": 0.3}'
json.loads(s)

the code above doesn't throw an exception, while the string is obviously not a valid JSON according to my backend friend and jsonlint.com/.

What should I do?

1
  • why do you think it cannot valid? Commented Aug 25, 2022 at 10:31

3 Answers 3

3

By default json.loads accepts '-Infinity', 'Infinity', 'NaN' as values. But you can control this by using parse_constant parameter.

Quoting from the documentation,

if it specified, will be called with one of the following strings: '-Infinity', 'Infinity', 'NaN'. This can be used to raise an exception if invalid JSON numbers are encountered

Sign up to request clarification or add additional context in comments.

Comments

0

You can use parse_constant, documentation says:

if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered.

For example:

import json

s = '{"position": NaN, "score": 0.3}'


def validate(val):
    if val == 'NaN':
        raise ValueError('Nan is not allowed')
    return val


print(json.loads(s, parse_constant=validate))

Comments

0

According to json.JSONDecoder documentation - "It also understands NaN, Infinity, and -Infinity as their corresponding float values, which is outside the JSON spec. [...] parse_constant, if specified, will be called with one of the following strings: '-Infinity', 'Infinity', 'NaN'. This can be used to raise an exception if invalid JSON numbers are encountered."

import json

def exc(x):
    raise ValueError(f"{x} is not a valid JSON object")

s = '{"position": Infinity, "score": 0.3}'

d = json.loads(s, parse_constant=exc)
print(d)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.