如何使用Python在{...}中grep单词

2guxujil  于 2023-06-04  发布在  Python
关注(0)|答案(2)|浏览(93)

我想grep唯一的值:“INC1301724”来自“display_value”:“INC1301724”,来自文本文件:Response.txt如下:

print('Response after Snow ticket update : '+response.text)

response.text的值为:

{"import_set":"ISET1677878","staging_table":"u_incident_create_import","result":[{"transform_map":"Incident Create Import","table":"incident","display_name":"number","display_value":"INC1301724","record_link":"https://example.com/api/now/table/incident/04331234rfgthyjjkkkkllljhfdd","status":"inserted","sys_id":"01234567890"}]}
nkoocmlb

nkoocmlb1#

你只需要在每一行中搜索“display_value”,然后用search about index of '"'剪切子字符串:this is image of the Solution

with open('response.txt') as file:
for line in file:
    String_Line=line.rstrip()
    if "display_value" in String_Line:
        index1 = String_Line.find ( 'display_value":' )
        Newstring=String_Line[index1+16:]
        print(Newstring)
        new_index_1 = Newstring.find('"')
        print(new_index_1)
        your_string=Newstring[:new_index_1]
        print(your_string)
3okqufwl

3okqufwl2#

使用json

json.loads('{"import_set":"ISET1677878","staging_table":"u_incident_create_import","result":[{"transform_map":"Incident Create Import","table":"incident","display_name":"number","display_value":"INC1301724","record_link":"https://example.com/api/now/table/incident/04331234rfgthyjjkkkkllljhfdd","status":"inserted","sys_id":"01234567890"}]}')["result"][0]["display_value"]

相关问题