<分区>
我正在处理 numpy.float32
数字,它们不会进入 JSON
。克服这个问题的正确方法是什么?
import numpy as np
import json
a = np.float32(1)
json.dumps(a)
TypeError: Object of type 'float32' is not JSON serializable
<分区>
我正在处理 numpy.float32
数字,它们不会进入 JSON
。克服这个问题的正确方法是什么?
import numpy as np
import json
a = np.float32(1)
json.dumps(a)
TypeError: Object of type 'float32' is not JSON serializable
最佳答案
它必须是一个字符串,所以你可以:
json.dumps(str(a))
编辑:
JSON 是一种序列化对象数据的格式。它并不真正关心或了解 Python 类型,json 包会尝试通过 转换表
将您传递给 json.dumps()
的任何对象转换为字符串形式仅支持某些类型(请参阅下面的文档)。
这就是为什么我认为只传递一个字符串来避免这个问题是个好主意的原因:numpy.float32
只是不在表中。
因为有些人评论说将字符串显式传递给 dumps
“听起来不对”,我将在此处添加文档
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) Serialize obj to a JSON formatted str using this conversion table. The arguments have the same meaning as in dump().
Note Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys.
关于python - 类型错误 : Object of type 'float32' is not JSON serializable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53082708/