gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:34:55 25 4
gpt4 key购买 nike

我正在尝试使用 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。看着 sourcedocumentation为此,我们看到它是为了返回一个列表。因此,您应该将其视为列表而不是需要解码的字符串。

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

关于python - 带有 Python 的 JSON "object must be str, not dict",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35928298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com