📅  最后修改于: 2020-09-06 09:52:33             🧑  作者: Mango
在Python中加载并解析具有多个JSON对象的JSON文件时,会遇到json.decoder.JSONDecodeError: Extra data error
的错误,原因是json.load()只能处理单个JSON对象。
例如如下情况:
{"id": 1, "name": "Ault", "class": 8, "email": "ault@pynative.com"}
{"id": 2, "name": "john", "class": 8, "email": "jhon@pynative.com"}
{"id": 3, "name": "josh", "class": 8, "email": "josh@pynative.com"}
{"id": 4, "name": "emma", "class": 8, "email": "emma@pynative.com"}
如果文件包含多个JSON对象,则该文件无效。虽然每行都包含有效的JSON,但总体而言,它不是有效的JSON,因为没有顶级列表或对象定义。仅当存在顶级列表或对象定义时,我们才能将JSON称为有效JSON。
因此针对此种情况,我们的一般步骤如下:
jsonList
的空列表
json.loads()
将每个JSON对象成Python dict
import json
studentsList = []
print("Started Reading JSON file which contains multiple JSON document")
with open('students.txt') as f:
for jsonObj in f:
studentDict = json.loads(jsonObj)
studentsList.append(studentDict)
print("Printing each JSON Decoded Object")
for student in studentsList:
print(student["id"], student["name"], student["class"], student["email"])
打印输出如下:
Started Reading JSON file which contains multiple JSON document
Printing each JSON Decoded Object
1 Ault 8 ault@pynative.com
2 john 8 jhon@pynative.com
3 josh 8 josh@pynative.com
4 emma 8 emma@pynative.com