类型错误:bool_ 类型的对象不是 JSON 可序列化的 [英] TypeError: Object of type bool_ is not JSON serializable

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

问题描述

我正在尝试使用布尔格式的值之一将字典写入 json 文件.尝试运行代码时出现以下错误.

<块引用>

raise TypeError(f'Object of type {o.class.name} '类型错误:bool_ 类型的对象不是 JSON 可序列化的

我目前正在为此使用 Python.

解决方案

很可能是因为这个问题(或类似问题):

将 numpy 导入为 np导入jsonjson.dumps({"X": np.int32(5) > 5})

<块引用>

TypeError: 'bool_' 类型的对象不可 JSON 序列化

问题是你最终得到的是 bool_ 类型的东西,而不是 bool.

在任何类型错误的值上调用 bool() 都可以解决您的问题(假设您的 bool_ 版本与 numpy 的行为类似:

json.dumps({"X": bool(np.int32(5) > 5)})

<块引用>

'{"X": false}'

I am trying to write a dictionary to a json file with one of the values in boolean format. I get the following error when I am trying to run my code.

raise TypeError(f'Object of type {o.class.name} ' TypeError: Object of type bool_ is not JSON serializable

I am currently using Python for this purpose.

解决方案

It's likely because of this issue (or something similar):

import numpy as np
import json

json.dumps({"X": np.int32(5) > 5})

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

The issue is that you end up with something of type bool_ instead of bool.

Calling bool()on whichever value(s) are of the wrong type will fix your issue (assuming your version of bool_ behaves similarly to numpy's:

json.dumps({"X": bool(np.int32(5) > 5)})

'{"X": false}'

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

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