小编典典

Python-加载和解析具有多个JSON对象的JSON文件

python

我正在尝试在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— Python文档中的JSON编码器和解码器,但是通读这个看起来糟透了的文档非常令人沮丧。

前几行(用随机条目匿名):

{"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"}

阅读 1026

收藏
2020-02-18

共1个答案

小编典典

你有一个JSON Lines格式的文本文件。你需要逐行解析文件:

import json

data = []
with open('file') as f:
    for line in f:
        data.append(json.loads(line))

每行都包含有效的JSON,但总体而言,它不是有效的JSON值,因为没有顶级列表或对象定义。

请注意,由于该文件每行包含JSON,因此你无需麻烦地尝试一次性分析所有内容或找出流JSON解析器。现在,你可以选择在继续进行下一行之前分别处理每一行,从而节省了进程中的内存。如果文件很大,你可能不想将每个结果附加到一个列表中,然后再处理所有内容。

2020-02-18