|
|
|
|
|
當(dāng)你嘗試在 Python 中加載和解析包含多個(gè) JSON 對(duì)象的 JSON 文件時(shí),你如果收到一個(gè)錯(cuò)誤:json.decoder.JSONDecodeError: Extra data error. 原因是 json.load()
方法只能處理單個(gè) JSON 對(duì)象。
如果文件包含多個(gè) JSON 對(duì)象,則該文件無(wú)效。當(dāng)你嘗試加載和解析具有多個(gè) JSON 對(duì)象的 JSON 文件時(shí),每一行都包含有效的 JSON,但作為一個(gè)整體,它不是有效的 JSON,因?yàn)闆]有頂級(jí)列表或?qū)ο蠖x。只有當(dāng)存在頂級(jí)列表或?qū)ο蠖x時(shí),我們才能稱 JSON 為有效 JSON。
例如,你想讀取以下 JSON 文件,過(guò)濾一些數(shù)據(jù),并將其存儲(chǔ)到新的 JSON 文件中。
{"id": 1, "name": "json", "class": 8, "email": "json@webkaka.com"}
{"id": 2, "name": "john", "class": 8, "email": "jhon@webkaka.com"}
{"id": 3, "name": "josh", "class": 8, "email": "josh@webkaka.com"}
{"id": 4, "name": "emma", "class": 8, "email": "emma@webkaka.com"}
如果你的文件包含 JSON 對(duì)象列表,并且你想一次解碼一個(gè)對(duì)象,我們可以做到。要加載和解析具有多個(gè) JSON 對(duì)象的 JSON 文件,我們需要執(zhí)行以下步驟:
json.loads()
轉(zhuǎn)換每個(gè) JSON 對(duì)象為Python的dict
。現(xiàn)在讓我們看看這個(gè)例子。
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 json 8 json@webkaka.com
2 john 8 jhon@webkaka.com
3 josh 8 josh@webkaka.com
4 emma 8 emma@webkaka.com
由空格而不是行分隔的 json
如果我們有多個(gè)由空格而不是行分隔的 json,將如何實(shí)現(xiàn)這一點(diǎn)?代碼如下:
import json
studentsList = []
print("Started Reading JSON file which contains multiple JSON document")
with open('students.txt') as f:
braceCount = 0
jsonStr = ''
for jsonObj in f:
braceCount += jsonObj.count('{')
braceCount -= jsonObj.count('}')
jsonStr += jsonObj
if (braceCount == 0):
studentDict = json.loads(jsonStr)
studentsList.append(studentDict)
jsonStr = ''
print("Printing each JSON Decoded Object")
for student in studentsList:
print(student["id"], student["name"], student["class"], student["email"])