TypeError:"float32"类型的对象不可JSON序列化 [英] TypeError: Object of type 'float32' is not JSON serializable

查看:645
本文介绍了TypeError:"float32"类型的对象不可JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用numpy.float32数字,但它们没有加入JSON.什么是解决此问题的正确方法?

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

import numpy as np
import json

a = np.float32(1)
json.dumps(a)

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

推荐答案

它必须是字符串,因此您可以:

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

json.dumps(str(a))

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

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 table that only supports some types (see doc below).

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

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

因为有人评论说,将字符串显式传递给dumps听起来不对劲",所以我将在此处添加文档

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

json.dumps(obj,*,skipkeys = False,sure_ascii = True, check_circular = True,allow_nan = True,cls = None,indent = None, 分隔符=无,默认=无,sort_keys = False,** kw)将obj序列化为 使用此转换表的JSON格式的str.论据有 与dump()中的含义相同.

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().

注意JSON的键/值对中的键始终为str类型.什么时候 字典被转换成JSON,字典的所有键 被强制为字符串.结果,如果字典是 转换成JSON然后再返回一个字典,该字典 可能不等于原始版本.也就是说,如果x具有,loads(dumps(x))!= x 非字符串键.

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

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

这篇关于TypeError:"float32"类型的对象不可JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆