使用 Python 读取大型 JSON 文件时出错:"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行(,这个操作是成功的。

一个稍微清理过的Python 3版本的BoboDarph代码:

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上
  • Pandas>=0.13允许将生成器传递给DataFrame构造函数
  • f字符串

详述上面的注释:数据文件中的一行或多行很可能不是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)

最新更新