首页 > 解决方案 > 如何读取包含多个 json 和使用的分隔符的文本文件是 Python 中带空格的新行

问题描述

我有一个文件,其中存在多个 JSON

{
  "schema": "2.0",
  "comp": [
    "fid1"
  ],
  "name": "Temp1",
  "type": "type1",
  "attr": {
    "version": "10.2.0.3"
  }
}

{
  "time": "18:21:58",
  "process": "Start",
  "msg": "Start"
}

我想将其解析为多个 JSON 对象。我尝试使用 json.load 但由于它不是纯 json 文件,它不起作用。其他选项是:

有没有其他方法可以解析并且即使文件大小增加也可以适应?此外,文件中的 JSON 可以不同。

标签: pythonjsonparsingjsonparser

解决方案


将其作为字符串处理并使用堆栈保存“{”(不能用于键或值包含单个{}}\w*{):

import json
# use open() function to open your text file.
my_json = ''' 
{
  "schema": "2.0",
  "comp": [
    "fid1"
  ],
  "name": "Temp1",
  "type": "type1",
  "attr": {
    "version": "10.2.0.3"
  }
}

{
  "time": "18:21:58",
  "process": "Start",
  "msg": "Start"
}
'''
stack = []
jsonstr = ""
json_list = []
for i in range(len(my_json)):
    if my_json[i] == '{':
        stack.append("{")
    jsonstr += my_json[i]
    if my_json[i] == '}':
        stack.pop()
        if not stack: # if stack is empty
            # now you can write it in a file

            # with open("json_{}.json".format(index),'w+') as f:
            #     f.write(jsonstr.strip())

            # convert it to a json object
            jsonList.append(json.loads(jsonstr))
            jsonstr = ""

for i in jsonList:
    print(i)

结果:

{'schema': '2.0', 'comp': ['fid1'], 'name': 'Temp1', 'type': 'type1', 'attr': {'version': '10.2.0.3'}}
{'time': '18:21:58', 'process': 'Start', 'msg': 'Start'}

推荐阅读