简体   繁体   English

在 python 中处理 json.loads() 值错误

[英]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.我浏览了一些博客并意识到 ujson 在执行json.loads操作时不会处理nanNaN值。

My final goal: I want to我的最终目标:我要

  1. use ujson to load the string into JSON-FORMAT使用 ujson 将字符串加载到 JSON-FORMAT
  2. handle this type of VALUE ERRORS处理这种类型的值错误
  3. load the input string into JSON将输入字符串加载到 JSON 中

Note:my input might be nested json structure注意:我的输入可能是嵌套的 json 结构

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 . NaN不是有效的 JSON 符号,请参阅http://json.org/ 上的规范ujson不支持nan / inf加载。 See https://github.com/ultrajson/ultrajson/issues/146 for more info有关更多信息,请参阅https://github.com/ultrajson/ultrajson/issues/146

In my opinion attempt to replace nan with null is prone to errors.在我看来,尝试用null替换nan容易出错。 use json from Standard Library.使用标准库中的json Here is link to relevant part of the docs这是文档相关部分的链接

The best options is to use jsonpickle to serialize the numpy values properly.最好的选择是使用 jsonpickle 正确序列化 numpy 值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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