簡體   English   中英

在Python中讀取大型JSON文件

[英]Reading large JSON file in Python

我有一個約5GB的大型JSON文件,但是它不是由一個JSON文件組成,而是將多個文件串聯在一起。

{"created_at":"Mon Jan 13 20:01:57 +0000 2014","id":422820833807970304,"id_str":"422820833807970304"}
{"created_at":"Mon Jan 13 20:01:57 +0000     2014","id":422820837545500672,"id_str":"422820837545500672"}.....

大括號} {之間沒有換行。

我嘗試使用sed用換行符替換大括號,然后使用以下命令讀取文件:

data=[]
for line in open(filename,'r').readline():
data.append(json.loads(line))

但這是行不通的。

如何相對快速地讀取此文件?

任何幫助,不勝感激

這是一個hack。 它不會將整個文件加載到內存中。 我真的希望您使用Python 3。

DecodeLargeJSON.py

from DecodeLargeJSON import *
import io
import json

# create a file with two jsons
f = io.StringIO()
json.dump({1:[]}, f)
json.dump({2:"hallo"}, f)
print(repr(f.getvalue()))
f.seek(0) 

# decode the file f. f could be any file from here on. f.read(...) should return str
o1, idx1 = json.loads(FileString(f), cls = BigJSONDecoder)
print(o1) # this is the loaded object
# idx1 is the index that the second object begins with
o2, idx2 = json.loads(FileString(f, idx1), cls = BigJSONDecoder)
print(o2)

如果您發現某些無法解碼的對象,則可以告訴我,我們可以找到解決方案。

免責聲明這不是有效的最佳解決方案。 它是一個黑客,展示了如何使其成為可能。

討論因為它不會將整個文件加載到內存中,所以正則表達式不起作用。 它還使用Python實現而不是C實現。 這可能會使速度變慢。 我真的很討厭這個簡單的任務很難。 希望其他人指出另一種解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM