如何从python3的资源流加载json

2024-09-30 22:20:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将resource_streamfrompkg_resourcesjson.load结合使用,在python3中遇到了python2中没有的问题。在

当我尝试运行以下命令时,我得到错误:

loaded_json = json.load(resource_stream(__name__, 'path/to/foo.json'))

>> TypeError: the JSON object must be str, not 'bytes'

Tags: topathname命令jsonstreamfoo错误
1条回答
网友
1楼 · 发布于 2024-09-30 22:20:07

在Python 3中,json.load不再支持从bytestream读取,您必须在解析它之前对其进行解码:

json_string = resource_stream(__name__, 'path/to/foo.json').read().decode()
loaded_json = json.loads(json_string)

相关问题 更多 >