簡體   English   中英

在Python中解析大型JSON文件

[英]Parse large JSON file in Python

我正在嘗試用Python解析一個非常大的JSON文件。 該文件有6523440行,但分為很多JSON對象。

結構如下所示:

[
  {
    "projects": [
     ...
    ]
  }
]
[
  {
    "projects": [
     ...
    ]
  }
]
....
....
....

它一直持續......

每次我嘗試使用json.load()加載它時都會出錯

ValueError: Extra data: line 2247 column 1 - line 6523440 column 1 (char 101207 - 295464118)

在第一個對象結束而第二個對象開始的行上。 有沒有辦法單獨加載它們或類似的東西?

您可以嘗試使用像ijson這樣的流式json庫:

有時在處理特別大的JSON有效負載時,甚至可能不構造單個Python對象並對單個事件做出反應,立即產生一些結果

嘗試使用json.JSONDecoder.raw_decode 它仍然要求您將整個文檔放在內存中,但允許您從一個字符串迭代地解碼許多對象。

import re
import json

document = """
[
    1,
    2,
    3
]
{
    "a": 1,
    "b": 2,
    "c": 3
}
"""

not_whitespace = re.compile(r"\S")

decoder = json.JSONDecoder()

items = []
index = 0
while True:
    match = not_whitespace.search(document, index)
    if not match:
        break

    item, index = decoder.raw_decode(document, match.start())
    items.append(item)

print(items)

暫無
暫無

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

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