如何读取包含多个json和使用分隔符的文本文件是Python中带有空格的新行

2024-09-24 02:21:56 发布

您现在位置: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。这种方法的缺点是,如果文件太大,它会很复杂
  • 基于新线和空间进行拆分

有没有其他方法可以进行解析,并且即使文件大小增加也可以进行调整?此外,文件中的JSON可能不同


Tags: 文件方法namejsontimeversionschematype
1条回答
网友
1楼 · 发布于 2024-09-24 02:21:56

将其作为字符串处理并使用堆栈保存“{”(无法用于键或值包含单个{}}\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'}

相关问题 更多 >