首页 > 解决方案 > 如何解析包含多个对象的单行 json 文件

问题描述

我需要读取一些 JSON 数据进行处理。我有一个包含多个 JSON 对象的单行文件,我该如何解析它?

我希望输出是一个文件,每个对象只有一行。

我尝试了一种蛮力方法,它将递归地使用 json.loads 来检查 json 是否有效,但每次运行程序时都会得到不同的结果

import json

with open('sample.json') as inp:
s = inp.read()

jsons = []

start, end = s.find('{'), s.find('}')
while True:
 try:
    jsons.append(json.loads(s[start:end + 1]))
    print(jsons)
except ValueError:
    end = end + 1 + s[end + 1:].find('}')
else:
    s = s[end + 1:]
    if not s:
        break
    start, end = s.find('{'), s.find('}')

for x  in jsons:
  writeToFilee(x)

json格式可以看这里 https://pastebin.com/DgbyjAG9

标签: pythonjsonpython-3.x

解决方案


为什么不直接使用 的pos属性JSONDecodeError来告诉你在哪里划界呢?

就像是:

import json

def json_load_all(buf):
    while True:
        try:
            yield json.loads(buf)
        except json.JSONDecodeError as err:
            yield json.loads(buf[:err.pos])
            buf = buf[err.pos:]
        else:
            break

与您的演示数据一起使用:

with open('data.json') as fd:
    arr = list(json_load_all(fd.read()))

正好给了我两个元素,但我想你还有更多?

要使用标准库完成此操作,写出如下所示:

with open('data.json') as inp, open('out.json', 'w') as out:
    for obj in json_load_all(inp.read()):
        json.dump(obj, out)
        print(file=out)

否则这个jsonlines包很适合处理这种数据格式


推荐阅读