将JSON文件加载到python中的代码不是一行一行地包含许多对象的



我能够使用以下代码将JSON文件加载到python中

with open(json_file, 'r') as f:
json_data = [line for line in json.load(f)]

但只有当json文件按如下所示逐行显示时,这才会起作用:

[
{"sepalLength": 5.1, "sepalWidth": 3.5, "petalLength": 1.4, "petalWidth": 0.2, "species": "setosa"},
{"sepalLength": 4.9, "sepalWidth": 3.0, "petalLength": 1.4, "petalWidth": 0.2, "species": "setosa"},
{"sepalLength": 4.7, "sepalWidth": 3.2, "petalLength": 1.3, "petalWidth": 0.2, "species": "setosa"},
{"sepalLength": 4.6, "sepalWidth": 3.1, "petalLength": 1.5, "petalWidth": 0.2, "species": "setosa"}
]

如果json数据集如下:

[
{"sepalLength": 5.1,
"sepalWidth": 3.5,
"petalLength": 1.4,
"petalWidth": 0.2,
"species": "setosa"},
{"sepalLength": 5.1,
"sepalWidth": 3.5,
"petalLength": 1.4,
"petalWidth": 0.2,
"species": "setosa"}
]

如何将文件加载到python中?

编辑:这是我在网上下载json数据集时遇到的错误:

Traceback (most recent call last):
File "test.py", line 12, in <module>
json_data = json.load(f)
File "C:UsersgeorgAppDataLocalProgramsPythonPython38-32libjson__init__.py", line 293, in load
return loads(fp.read(),
File "C:UsersgeorgAppDataLocalProgramsPythonPython38-32libencodingscp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 768: character maps to <undefined>

我建议您使用json.load()并设置打开文件的编码。

with open(json_file, 'r', encoding="utf8") as f:
json_data = json.load(f)

最新更新