如何读取包含多个 json 且使用的分隔符是 Python 中带有 space 的新行的文本文件
How to read text file which contains multiple json and delimiter used is new line with space in 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。这种方法的缺点是如果文件太大就会很复杂
- 根据新行和 space 拆分。
是否有任何其他解析方式,即使文件大小增加也能适应?此外,文件中的 JSON 可以不同。
将其作为字符串处理并使用堆栈保存“{”(不能用于包含单个 {
、}
或 }\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'}
我有一个文件,其中存在多个 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。这种方法的缺点是如果文件太大就会很复杂
- 根据新行和 space 拆分。
是否有任何其他解析方式,即使文件大小增加也能适应?此外,文件中的 JSON 可以不同。
将其作为字符串处理并使用堆栈保存“{”(不能用于包含单个 {
、}
或 }\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'}