How to read text file which contains multiple json and delimiter used is new line with space in Python [closed]

人盡茶涼 提交于 2020-06-23 18:03:59

问题


I have a file where multiple JSON are present

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

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

I want to parse this into multiple JSON objects. I tried to use json.load but since it is not a pure json file it does not work. Other options are :

  • Read like string and bases on start and end bracket, capture JSON. The downside of this approach is if the file is too big it's going to be complex
  • Split based on new line and space.

Is there any other way to parse and that can adapt even if file size grows? Also, JSON within the file can be different.


回答1:


Handle it as a string and use a stack to save the "{"(Couldn't be used to key or value contains single {,} or }\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)

result:

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


来源:https://stackoverflow.com/questions/61114568/how-to-read-text-file-which-contains-multiple-json-and-delimiter-used-is-new-lin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!