【问题标题】:Handling json.loads() Value Error in python在 python 中处理 json.loads() 值错误
【发布时间】:2021-01-18 18:29:06
【问题描述】:

当我尝试运行此代码时遇到错误。

import ujson as json

input = '{"a":NaN}'
print(json.loads(input))

错误

print(json.loads(input))
ValueError: Expected object or value

我浏览了一些博客,发现 ujson 在执行json.loads 操作时不会处理nanNaN 值。

我的最终目标: 我想要

  1. 使用ujson将字符串加载到JSON-FORMAT中
  2. 处理这种类型的 VALUE ERRORS
  3. 将输入字符串加载到 JSON 中

注意:我的输入可能是嵌套的 json 结构

input = {"name":"siva","details":{"id":"111","qualification":nan},"marks":[{"grade1":90,"grade2":null,"grade3":NaN}]}

预期输出

{"a":NaN}
{"name":"siva","details":{"id":"111","qualification":nan},"marks":[{"grade1":90,"grade2":null,"grade3":NaN}]}


谁能为此提出解决方案?

【问题讨论】:

  • 为什么不使用json 而不是ujson?它适用于你的例子
  • 解析json时不能处理值错误。它要么完全正确,要么有错误。如果你想检测无效值,你必须自己做。您的意思是:'input = '{"a":null}'。 ?
  • @SpiderPig1297, ujsonjson 快,这就是为什么我要使用ujson
  • 顺便说一句,不要使用input作为变量名

标签: python json python-3.x ujson


【解决方案1】:

我不确定您寻求的预期输出是什么(如果您也可以添加它会很棒)。

以下代码将执行而不会出现任何错误:

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

【讨论】:

  • 我只想按原样提取 JSON-STRING。供您参考,我添加了示例输出。请检查一下。
  • @siva 您无法获得所需的输出,但使用json 您将能够尽可能接近它,但您仍然需要使用re.sub 来更改nan,因为它只识别NaN
【解决方案2】:

NaN 不是有效的 JSON 符号,请参阅 http://json.org/ 的规范 ujson 不支持 nan/inf 的加载。请参阅https://github.com/ultrajson/ultrajson/issues/146 了解更多信息

在我看来,用null 替换nan 很容易出错。 使用标准库中的json。这是relevant part of the docs的链接

【讨论】:

  • 标准json 库句柄是nan 还是NaN 值?
  • 是的 - 检查docs
【解决方案3】:

最好的选择是使用 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())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-16
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多