Skip to main content
 首页 » 编程设计

python之带有 Python 的 JSON "object must be str, not dict"

2025年05月04日8bluestorm

我正在尝试使用 Python 解释来自 Twitch API 的数据。这是我的代码:

from twitch.api import v3 
import json 
 
streams = v3.streams.all(limit=1) 
list = json.loads(streams)  
print(list)  

然后,在运行时,我得到:

TypeError, "the JSON object must be str, not 'dict'"

有什么想法吗?另外,这是我实际上想要使用来自 API 的数据的方法吗?

请您参考如下方法:

根据 documentation json.loads() 会将字符串解析为 json 层次结构(通常是 dict)。因此,如果您不向它传递字符串,它将失败。

json.loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) Deserialize s (a str instance containing a JSON document) to a Python object using this conversion table.

The other arguments have the same meaning as in load(), except encoding which is ignored and deprecated.

If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.

来自Twitch API我们看到 all() 返回的对象是一个 V3Query。看着 source和 documentation为此,我们看到它是为了返回一个列表。因此,您应该将其视为列表而不是需要解码的字符串。

具体来说,V3Query 是 ApiQuery 的子类,又是 JsonQuery 的子类。该类显式运行查询并在结果上传递一个函数,get_json .该源显式调用 json.loads()...所以您不需要!请记住:永远不要害怕挖掘源代码。