加载并解析包含多个 JSON 对象的 JSON 文件
- 2024-12-13 08:36:00
- admin 原创
- 124
问题描述:
我正在尝试用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)
我查看了Python 文档中的18.2. json
— 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"}
解决方案 1:
您有一个JSON 行格式的文本文件。您需要逐行解析文件:
import json
data = []
with open('file') as f:
for line in f:
data.append(json.loads(line))
每一行都包含有效的 JSON,但作为一个整体,它不是一个有效的 JSON 值,因为没有顶级列表或对象定义。
请注意,由于文件每行都包含 JSON,因此您无需费心尝试一次性解析所有内容或找出流式 JSON 解析器。您现在可以选择在继续处理下一行之前单独处理每一行,从而节省内存。如果您的文件非常大,您可能不想将每个结果附加到一个列表中,然后处理所有内容。
如果您有一个包含各个 JSON 对象且其间有分隔符的文件,请使用如何使用“json”模块一次读取一个 JSON 对象?使用缓冲方法解析出各个对象。
解决方案 2:
如果您正在使用pandas
并且有兴趣将json
文件作为数据框加载,则可以使用:
import pandas as pd
df = pd.read_json('file.json', lines=True)
要将其转换为 json 数组,可以使用:
df.to_json('new_file.json')
解决方案 3:
对于那些偶然发现这个问题的人:pythonjsonlines
库(比这个问题年轻得多)优雅地处理每行一个 json 文档的文件。请参阅https://jsonlines.readthedocs.io/
解决方案 4:
就像Martijn Pieters 的答案一样,但可能更具 Python 风格,最重要的是,它支持数据流(参见答案的第二部分):
import json
with open(filepath, "r") as f:
return list(map(json.loads, f))
函数map(function, iterable)
返回一个适用function
于 的每个项目的迭代器iterable
,产生结果(参见map() python doc)。
并将list
此迭代器转换为...列表 :)
但您可以想象直接使用 map 返回的迭代器:它会迭代您的每个 json 行。请注意,在这种情况下,您需要在上下文中执行此操作with open(filepath, "r") as f
:这是这种方法的优势,json 行未完全加载到列表中,它们是流式传输的next(iterator)
:当调用时,map 函数会读取文件的每一行for loop
。
它会给出:
import json
with open(file path, "r") as f:
iterator_over_lines = map(json.loads, f)
# just as you would do with a list but here the file is streamed
for jsonline in iterator_over_lines:
# do something for each line
# the function mapped, json.loads is only call on each iteration
# that's why the file must stay opened
# You can try to call yourself the next function used by the for loop:
next_jsonline = next(iterator_over_lines)
nextnext_jsonline = next(iterator_over_lines)
对于 Martijn 的回答中关于什么是 jsonl(json 逐行文件)以及为什么使用它的解释,我没有什么可补充的!
解决方案 5:
格式不正确。每行有一个 JSON 对象,但它们不包含在更大的数据结构(即数组)中。您要么需要重新格式化它,使其以逗号开头[
和结尾,要么逐行解析它作为单独的字典。]
解决方案 6:
对@arunppsg 的答案进行补充,但使用多处理来处理目录中的大量文件。
import numpy as np
import pandas as pd
import json
import os
import multiprocessing as mp
import time
directory = 'your_directory'
def read_json(json_files):
df = pd.DataFrame()
for j in json_files:
with open(os.path.join(directory, j)) as f:
df = df.append(pd.read_json(f, lines=True)) # if there's multiple lines in the json file, flag lines to true, false otherwise.
return df
def parallelize_json(json_files, func):
json_files_split = np.array_split(json_files, 10)
pool = mp.Pool(mp.cpu_count())
df = pd.concat(pool.map(func, json_files_split))
pool.close()
pool.join()
return df
# start the timer
start = time.time()
# read all json files in parallel
df = parallelize_json(json_files, read_json)
# end the timer
end = time.time()
# print the time taken to read all json files
print(end - start)