python - 类型错误 : Object of type 'float32' is not JSON serializable

标签 python json numpy

<分区>

我正在处理 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.

摘自此处的官方文档:https://docs.python.org/3/library/json.html

关于python - 类型错误 : Object of type 'float32' is not JSON serializable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53082708/

相关文章:

python - Python 的标准库中有没有类似循环函数的函数?

php - 解析 JSON 数组 PHP - 字符串和 float

Python fmin 太慢

python - 大于阈值的元素的 numpy.argmin

java - 将 Gson 数组转换为 Arraylist

python - 在 numpy 数组的每一行中查找第一次出现的整数索引的最佳方法?

python - 用 Python 从 NYT 文件中抓取完整的文章?

python - 如何使用 xpath 从父级 html 中检索嵌套和非嵌套子级?

python - 我收到 AttributeError : 'NoneType' object has no attribute 'find'

javascript - 映射单元格以在 HTML 表格中显示 JSON 数据