![](/img/trans.png)
[英]Python Json.decoder.JSONDecodeError: Expecting ',' delimiter:
[英]Error while reading a big JSON file with Python: “json.decoder.JSONDecodeError: Expecting ',' delimiter”
我試圖用Python讀取一個大的json文件(大約3 Go)。 該文件實際上包含大約700萬個json對象(每行一個)。
我嘗試了很多不同的解決方案,但我一直遇到相同的錯誤:
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 25 (char 24)
我正在使用的代碼在這里:
import json
import pandas as pd
with open('mydata.json') as json_file:
data = json_file.readlines()
# this line below may take at least 8-10 minutes of processing for 4-5
# million rows. It converts all strings in list to actual json objects.
data = list(map(json.loads, data))
pd.DataFrame(data)
關於我為什么會收到此錯誤的任何想法? 它似乎與文件的格式有關,但原則上是正確的json格式(我已經通過https://jsonformatter.curiousconcept.com/檢查了幾行)。
我還嘗試讀取該文件的簡短版本(僅約30行),並且此操作成功。
BoboDarph的代碼經過稍微清理的Python 3版本:
import json
import logging
import pandas as pd
logger = logging.getLogger(__name__)
def iter_good_json_lines(lines):
for lineno, line in enumerate(lines, 1):
try:
yield json.loads(line.strip())
except json.JSONDecodeError as err:
logger.warning(f"lineno {lineno}:{err.colno} {err.msg}: {err.doc}")
with open('mydata.json') as fd:
data = pd.DataFrame(iter_good_json_lines(fd))
data
這會改變:
logging
模塊,這樣錯誤就不會在stdout上結束 DataFrame
構造函數 詳細說明以上注釋:數據文件中的一行或多行很可能不是JSON,因此Python嘗試將字符串加載到JSON對象時會出錯。
根據您的需求,您可以允許代碼失敗,因為您依賴該文件的所有行都是JSON,如果不是,則想知道(就像現在一樣),或者可以避免解析完全不使用JSON行,並在遇到任何情況時讓您的代碼發出警告。
要實現第二種解決方案,請將字符串包裝為JSON,然后將其包裝到try塊中,以清除所有有問題的行。 如果這樣做,所有非JSONS的行將被忽略,您的代碼將繼續嘗試解析所有其他行。
這是我將如何實現的方法:
import json
from json import JSONDecodeError
import pandas as pd
data = []
with open('mydata.json') as json_file:
for line in json_file.readlines():
js = None
try:
js = json.loads(line)
except JSONDecodeError:
print('Skipping line %s' %(line))
if js:
#You don't want None value in your dataframe
data.append(js)
test = pd.DataFrame(data)
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
print(test)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.