如何解析包含多个对象的单行json文件

2024-05-15 01:44:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要读取一些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


Tags: 文件数据对象方法程序jsonfindstart
3条回答

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

比如:

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

将演示数据用作:

^{pr2}$

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

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

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)

否则,^{}包适合处理这种数据格式

以下代码适用于我:

import json
with open(input_file_path) as f_in: 
    file_data = f_in.read() 
    file_data = file_data.replace("}{", "},{") 
    file_data = "[" + file_data + "]"
    data = json.loads(file_data)

@Chris A的评论之后,我准备了一个可以正常工作的片段:

with open('my_jsons.file') as file:
    json_string = file.read()

json_objects = re.sub('}\s*{', '}|!|{', json_string).split('|!|')
# replace |!| with whatever suits you best

for json_object in json_objects:
    print(json.loads(obj))

然而,这个例子一旦'}{'字符串出现在JSON中的某个值中,就会变得毫无价值,所以我强烈建议使用@Sam Mason的解决方案

相关问题 更多 >

    热门问题