我有一个文本文件,其中一个接一个地包含数千个 json 对象(即 json 的文本表示形式)。它们没有分开,我不想修改源文件。如何在 python 中加载/解析每个 json? (我见过 this question ,但如果我没记错的话,这只适用于 json 列表(已经用逗号分隔?)我的文件如下所示:
{"json":1}{"json":2}{"json":3}{"json":4}{"json":5}...
最佳答案
如果不使用真正的 JSON 解析器,我没有找到一种干净的方法来做到这一点。修改文本和使用非 JSON 解析器的其他选项都是有风险的。因此,最好的方法是找到一种使用真正的 JSON 解析器进行迭代的方法,这样您就可以确保遵守 JSON 规范。
核心思想是让真正的 JSON 解析器完成识别组的所有工作:
import json, re
combined = '{"json":1}{"json":2}{"json":3}{"json":4}{"json":5}'
start = 0
while start != len(combined):
try:
json.loads(combined[start:])
except ValueError as e:
pass
# Find the location where the parsing failed
end = start + int(re.search(r'column (\d+)', e.args[0]).group(1)) - 1
result = json.loads(combined[start:end])
start = end
print(result)
输出:
{u'json': 1}
{u'json': 2}
{u'json': 3}
{u'json': 4}
{u'json': 5}
关于迭代存储在文本文件中的 json 对象集合的 pythonic 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31164021/