问题
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/61117007/parse-text-file-which-has-multiple-json-using-python