Reputation: 629
when I try to run this code I am experiencing an error.
import ujson as json
input = '{"a":NaN}'
print(json.loads(input))
Error
print(json.loads(input))
ValueError: Expected object or value
I gone through some blogs and realized that ujson won't handle nan
or NaN
values while performing json.loads
operation.
My final goal: I want to
Note:my input might be nested json structure
input = {"name":"siva","details":{"id":"111","qualification":nan},"marks":[{"grade1":90,"grade2":null,"grade3":NaN}]}
Expected output
{"a":NaN}
{"name":"siva","details":{"id":"111","qualification":nan},"marks":[{"grade1":90,"grade2":null,"grade3":NaN}]}
Can anyone suggest a solution for this?
Upvotes: -1
Views: 3106
Reputation: 2563
The best options is to use jsonpickle to serialize the numpy values properly.
import jsonpickle
import jsonpickle.ext.numpy as jsonpickle_numpy
jsonpickle_numpy.register_handlers()
with open('file.json', 'wb') as _file:
_file.write(jsonpickle.encode(pairs).encode())
with open('file.json', 'rb') as _file:
unpacked = jsonpickle.decode(_file.read())
Upvotes: 0
Reputation: 14273
NaN
is not a valid JSON symbol, see the spec at http://json.org/
ujson
does not support load of nan
/inf
. See https://github.com/ultrajson/ultrajson/issues/146 for more info
In my opinion attempt to replace nan
with null
is prone to errors.
use json
from Standard Library. Here is link to relevant part of the docs
Upvotes: 0
Reputation: 8318
I'm not sure what is the expected output that you seek (it will be great if you could also add it).
The following code will perform without any errors:
import json
import re
in1 = '{"Number": nan}'
in1 = re.sub(r'\bnan\b', 'NaN', in1)
print(json.loads(in1))
# {'Number': nan}
in2 = '{"name":"siva","details":{"id":"111","qualification":nan},"marks":[{"grade1":90,"grade2":null,"grade3":NaN}]}'
in2 = re.sub(r'\bnan\b', 'NaN', in2)
print(json.loads(in2))
# {'name': 'siva', 'details': {'id': '111', 'qualification': nan}, 'marks': [{'grade1': 90, 'grade2': None, 'grade3': nan}]}
Upvotes: 0