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

Gre*_*reg 6 python import text json

使用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')]
Run Code Online (Sandbox Code Playgroud)

但是我收到了错误:

the JSON object must be str, not 'bytes'
Run Code Online (Sandbox Code Playgroud)

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

Sha*_*ger 3

以文本模式打开文件,而不是二进制模式(可能显式传递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]
Run Code Online (Sandbox Code Playgroud)