我正在尝试加载和解析 Python 中的 JSON 文件.但我一直在尝试加载文件:
import json
json_data = open('file')
data = json.load(json_data)
产量:
ValueError: Extra data: line 2 column 1 - line 225116 column 1 (char 232 - 160128774)
我看了 18.2. json
— JSON encoder and decoder 在 Python 文档中,但是阅读这个看起来很糟糕的文档是非常令人沮丧的。
前几行(以随机条目匿名):
{"votes": {"funny": 2, "useful": 5, "cool": 1}, "user_id": "harveydennis", "name": "Jasmine Graham", "url": "http://example.org/user_details?userid=harveydennis", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 2, "cool": 4}, "user_id": "njohnson", "name": "Zachary Ballard", "url": "https://www.example.com/user_details?userid=njohnson", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 0, "cool": 4}, "user_id": "david06", "name": "Jonathan George", "url": "https://example.com/user_details?userid=david06", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 6, "useful": 5, "cool": 0}, "user_id": "santiagoerika", "name": "Amanda Taylor", "url": "https://www.example.com/user_details?userid=santiagoerika", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 8, "cool": 2}, "user_id": "rodriguezdennis", "name": "Jennifer Roach", "url": "http://www.example.com/user_details?userid=rodriguezdennis", "average_stars": 3.5, "review_count": 12, "type": "user"}
最佳答案
您有一个 JSON Lines format text file .您需要逐行解析文件:
import json
data = []
with open('file') as f:
for line in f:
data.append(json.loads(line))
每一行都包含有效的JSON,但作为一个整体,它不是一个有效的JSON值,因为没有顶级列表或对象定义。
请注意,由于该文件每行都包含 JSON,因此您可以省去尝试一次性解析所有文件或找出流式 JSON 解析器的麻烦。您现在可以选择在继续下一行之前分别处理每一行,从而节省过程中的内存。如果您的文件很大,您可能不想将每个结果附加到一个列表中然后处理所有内容。
如果您的文件包含单独的 JSON 对象,中间有分隔符,请使用 How do I use the 'json' module to read in one JSON object at a time?使用缓冲方法解析出单个对象。
https://stackoverflow.com/questions/12451431/