python JSON对象必须为str,bytes或bytearray,而不是'dict [英] python JSON object must be str, bytes or bytearray, not 'dict

查看:278
本文介绍了python JSON对象必须为str,bytes或bytearray,而不是'dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 3中,要加载以前像这样保存的json:

In Python 3, to load json previously saved like this:

json.dumps(dictionary)

输出类似于

{"('Hello',)": 6, "('Hi',)": 5}

当我使用

json.loads({"('Hello',)": 6, "('Hi',)": 5})

它不起作用,发生这种情况:

it doesn't works, this happens:

TypeError:JSON对象必须是str,字节或字节数组,而不是'dict'

TypeError: the JSON object must be str, bytes or bytearray, not 'dict'

推荐答案

json.loads以字符串作为输入,并返回字典作为输出.

json.loads take a string as input and returns a dictionary as output.

json.dumps以字典作为输入,并返回一个字符串作为输出.

json.dumps take a dictionary as input and returns a string as output.

使用json.loads({"('Hello',)": 6, "('Hi',)": 5})

您正在使用字典作为输入来调用json.loads.

You are calling json.loads with a dictionary as input.

您可以按以下方式修复它(尽管我不太确定这是什么意思):

You can fix it as follows (though I'm not quite sure what's the point of that):

d1 = {"('Hello',)": 6, "('Hi',)": 5}
s1 = json.dumps(d1)
d2 = json.loads(s1)

这篇关于python JSON对象必须为str,bytes或bytearray,而不是'dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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