Python从输出解析JSON内容
我有一个输出,其中包含来自远程服务器的系统输出信息,在输出的最后,它包含一个JSON对象。像这样: 输出:Python从输出解析JSON内容,python,json,python-3.x,parsing,Python,Json,Python 3.x,Parsing,我有一个输出,其中包含来自远程服务器的系统输出信息,在输出的最后,它包含一个JSON对象。像这样: 输出: ... -Verification- -Test1: PASS -Test2: PASS ... ... Result: PASS ... #JSON Object below {"path": "/my/path/file.log", "name": "Roger", "year": 2018} 输出将只包含一组{},这就是我要解析的JSON对象。所以我们不必担心获取错误的信息 我想
...
-Verification-
-Test1: PASS
-Test2: PASS
...
...
Result: PASS
...
#JSON Object below
{"path": "/my/path/file.log", "name": "Roger", "year": 2018}
输出将只包含一组{}
,这就是我要解析的JSON对象。所以我们不必担心获取错误的信息
我想让我的flask应用程序解析这个输出,只返回JSON对象(包括{}
中的所有内容,包括{}
),并过滤上面的所有文本。我该怎么做呢?将正则表达式(re
)与表达式{.*}
import re
jsonstr='''...
-Verification-
-Test1: PASS
-Test2: PASS
...
...
Result: PASS
...
#JSON Object below
{"path": "/my/path/file.log", "name": "Roger", "year": 2018}'''
print(jsonstr.lstrip(re.sub('{.*}','',jsonstr)))
要定位JSON字符串,因为您知道其中没有其他“{”,请使用
str.find
和字符串索引:
json_loc = jsonstr.find('{')
if json_loc >= 0:
jsonstr = jsonstr[json_loc:]
else:
raise Exception("no JSON string found")
您是否尝试过使用
regex
?
json_loc = jsonstr.find('{')
if json_loc >= 0:
jsonstr = jsonstr[json_loc:]
else:
raise Exception("no JSON string found")