Python 类型错误:“float32”类型的对象不是 JSON 可序列化的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53082708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:15:20  来源:igfitidea点击:

TypeError: Object of type 'float32' is not JSON serializable

pythonjsonnumpy

提问by Franco Piccolo

I'm working with numpy.float32numbers and they don't go into JSON. What's the right approach to overcome this issue?

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

采纳答案by vencaslac

It has to be a string, so you can have:

它必须是一个字符串,所以你可以有:

json.dumps(str(a))

EDIT:

编辑:

JSON is a format for serialising object data. It doesn't really care or know about Python types, the json package tries to translate whatever object you pass json.dumps()into a string form via a conversion tablethat only supports some types (see doc below).

JSON 是一种用于序列化对象数据的格式。它并不真正关心或了解 Python 类型,json 包尝试json.dumps()通过conversion table仅支持某些类型的 将您传递的任何对象转换为字符串形式(请参阅下面的文档)。

This is the reason why I think it's a good idea to just pass a string to avoid this issue: numpy.float32just isn't in the table.

这就是为什么我认为只传递一个字符串来避免这个问题numpy.float32是个好主意的原因:只是不在表中。

Because some have commented that explicitly passing a string to dumps"sounds wrong" I'll just add the doc here

因为有些人评论说明确地将字符串传递给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.

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) 序列化obj使用此转换表转换为 JSON 格式的 str。这些参数的含义与 dump() 中的含义相同。

注意 JSON 的键/值对中的键始终为 str 类型。当字典转换为 JSON 时,字典的所有键都被强制转换为字符串。因此,如果将字典转换为 JSON,然后再转换回字典,则该字典可能不等于原始字典。也就是说,如果 x 具有非字符串键,则加载(dumps(x)) != x。

taken from the official docs here: https://docs.python.org/3/library/json.html

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