简体   繁体   English

我如何在 Python 中序列化 json?

[英]How I can serialize the json in Python?

Here is the code and the error follows:这是代码,错误如下:

import numpy as np
import json
X=np.arange(20)
t=dict(x=list(X))
print(json.dumps(t))

The error is:错误是:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python35\lib\json\__init__.py", line 230, in dumps
    return _default_encoder.encode(obj)
  File "C:\Python35\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Python35\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Python35\lib\json\encoder.py", line 180, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: 0 is not JSON serializable

Please let me know what I can do to get rid of this.请让我知道我能做些什么来摆脱这种情况。 I am trying to pass this value to the plotting windows and the same error is occurring.我正在尝试将此值传递给绘图窗口,并且发生了相同的错误。

Another way is to use tolist method.另一种方法是使用tolist方法。 This will return a copy of the array data as a (nested) Python list.这将返回数组数据的副本作为(嵌套的)Python 列表。 For a 1D array, a.tolist() is almost the same as list(a) .However, for a 2D array, tolist applies recursively:对于一维数组, a.tolist()几乎与list(a)相同。但是,对于二维数组, tolist递归应用:

>>> import numpy as np
>>> import json

>>> X = np.arange(20)
>>> t = dict(x=X.tolist())
>>> print(json.dumps(t))
{"x": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]}

I think that's because json doesn't recognize the numpy data type.我认为这是因为json无法识别 numpy 数据类型。

I tried this code and it worked.我试过这段代码,它奏效了。

import json
t= {'x': [i for i in range(20)]}
print(json.dumps(t))

One approach mapping int on array在数组上映射int一种方法

Ex:前任:

import numpy as np
import json
X=np.arange(20)
t=dict(x=list(map(int, X)))
print(json.dumps(t))

Your json values are not properly type cast I guess.我猜您的 json 值类型转换不正确。 tried to find something related to your query: TypeError: Object of type 'int64' is not JSON serializable试图找到与您的查询相关的内容: TypeError: Object of type 'int64' is not JSON serializable

You just need to type cast it:你只需要输入它:

>>> t = dict(x=list(float(j) for j in X))
>>> json.dumps(t)
'{"x": [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0]}'

I guess that will work.我想这会奏效。

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

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