简体   繁体   中英

Handling json.loads() Value Error in python

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

  1. use ujson to load the string into JSON-FORMAT
  2. handle this type of VALUE ERRORS
  3. load the input string into JSON

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?

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}]}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM