python - 来自 json.dumps 的奇怪类型错误

标签 python json python-3.x numpy dictionary

在 python 3.4.0 中,在一种情况下使用 json.dumps() 会抛出一个 TypeError,但在另一种情况下就像一个魅力(我认为这等同于第一个)。

我有一个字典,其中键是字符串,值是数字和其他字典(例如 {'x': 1.234, 'y': -5.678, 'z': {'a': 4, 'b': 0, 'c': -6}}).

这失败了(堆栈跟踪不是来自这个特定的代码片段,而是来 self 的更大的脚本,我不会在这里粘贴它,但它本质上是相同的):

>>> x = dict(foo()) # obtain the data and make a new dict of it to really be sure
>>> import json
>>> json.dumps(x)
Traceback (most recent call last):
  File "/mnt/data/gandalv/progs/pycharm-3.4/helpers/pydev/pydevd.py", line 1733, in <module>
    debugger.run(setup['file'], None, None)
  File "/mnt/data/gandalv/progs/pycharm-3.4/helpers/pydev/pydevd.py", line 1226, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/mnt/data/gandalv/progs/pycharm-3.4/helpers/pydev/_pydev_execfile.py", line 38, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc) #execute the script
  File "/mnt/data/gandalv/School/PhD/Other work/Krachy/code/recalculate.py", line 54, in <module>
    ls[1] = json.dumps(f)
  File "/usr/lib/python3.4/json/__init__.py", line 230, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python3.4/json/encoder.py", line 192, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.4/json/encoder.py", line 250, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python3.4/json/encoder.py", line 173, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: 306 is not JSON serializable

306x 中其中一个内部字典中的值之一。它并不总是相同的数字,有时它是字典中包含的不同数字,显然是因为字典的无序性。

然而,这就像一个魅力:

>>> x = foo() # obtain the data and make a new dict of it to really be sure
>>> import ast
>>> import json
>>> x2 = ast.literal_eval(repr(x))
>>> x == x2
True
>>> json.dumps(x2)
"{...}" # the json representation of dict as it should be

谁能告诉我为什么会发生这种情况或者可能是什么原因?最令人困惑的部分是这两个字典(原始字典和通过评估原始字典的表示形式获得的字典)是相等的,但 dumps() 函数对它们每个的行为不同。

最佳答案

原因是 dict 中的数字不是普通的 python int 而是 numpy.in64 显然不受支持json 编码器。

关于python - 来自 json.dumps 的奇怪类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25849850/

相关文章:

python - 我的 Keras 多输出神经网络是否因为没有足够的层数而未收敛?

c# - 声明变量以返回 Json 结果(ASP.NET MVC4)

python-3.x - python中的sigmoid,可以采用标量、向量或矩阵

python - 为什么比较两个分别包含一个 NumPy 对象的元组会报错?

python - Tkinter wm_attributes 没有 Linux 中的所有选项

python - 并行过程的最佳种子

python - Series.sort() 和 Series.order() 有什么区别?

python - 将python编解码器转换为文本

php - 尝试为 NVD3 图表创建 JSON 代码

json - 在 Elastic Search 中同步 JSON 数据