JSON对象必须是str,而不是'bytes'

2024-05-23 17:58:25 发布

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

使用Python 3.5.1,我拉入了一个文本文件,其中每一行都是JSON格式的: {“a”:“windows”,“b”:“stairs”…}

import json
path = 'folder/data.txt'
records=[json.loads(line) for line in open(path,'rb')]

但我收到了一个错误:

the JSON object must be str, not 'bytes'

打印第一行文件没有问题,所以我确信文件路径是正确的。


Tags: 文件pathimporttxtjsondatawindows格式
3条回答

您不想指定“rb”,因为JSON模块无法读取文件的二进制表示。你可能想要“utf-8”编码和“read”。编辑:我最初说过这两个都是默认值,但我注意到许多操作系统的默认编码不同,Python在open()中使用系统设置作为默认值。因此,我建议显式地将编码设置提供为“utf-8”。

json支持使用“json.load”而不是“json.loads”从打开的文件中加载,后者从字符串中加载,因此我们可以跳过作为文本的读入,直接转到json。我认为您不想“加载”单独的行,因为这可能不是有效的JSON。

import json
# open has __enter__ and __exit__ functions, so we can call it as a guard
# using "with" syntax and it'll close when the scope ends
with open(r".\myjson.json", encoding="utf-8") as fh:
    # load() is a convenience function to help us avoid iterating lines
    # on our own. It calls loads() on the whole doc and returns an obj
    json_obj = json.load(fh)
print (json_obj)

尝试: records=[json.loads(line.decode())for line in open(path,'rb')]

以文本模式而不是二进制模式打开文件(可能显式传递encoding='utf-8'以覆盖系统默认值,因为JSON通常存储为UTF-8)。json模块只接受str输入;从以二进制模式打开的文件中读取返回bytes对象:

# Using with statement just for good form; in this case it would work the
# same on CPython, but on other interpreters or different CPython use cases,
# it's easy to screw something up; use with statements all the time to build good habits
with open(path, encoding='utf-8') as f:
    records=[json.loads(line) for line in f]

相关问题 更多 >