Home > Blockchain >  JSON string validation in Python
JSON string validation in Python

Time:08-26

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?

CodePudding user response:

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

CodePudding user response:

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))

CodePudding user response:

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)
  • Related