I got dictionary from code below following this SO link
and need to get Application name,source and message for every key in dictionary so i tried to transfer it in JSON file
if mail["Subject"].find("example error alert") > 0 :
body = get_email_body(mail)
info = {}
segments = body.split(' ')
for line in body.splitlines():
if 'Application name' and 'null' in line:
info['test'] = segments[0] + ' ' + segments[1] + ' ' + segments[2] + ' ' + segments[3] + ' ' + segments[4]
elif 'Application name' in line:
info['test'] = segments[0] + ' ' + segments[1] + ' ' + segments[2] + ' ' + segments[3] + ' ' + segments[4] + ' ' + segments[5] + segments[6] + ' ' + segments[7] + ' ' + segments[8] + ' ' + segments[9]
r = json.dumps(info['test'])
loaded_r = json.loads(r)
print(str(r['Source']))
i have this dictionary
print(info['test'])
Application name: example.service
Source: example_host_1|exampleHost1
Timestamp: 2019-01-22T00:00:43.901Z
Message:
Application name: example.api
Source: example_host_2|exampleHost2
Timestamp: 2019-01-23T07:42:12.649Z
Message: HTTP"GET" "/api/endpoint/groups" responded 500
i converted it to JSON without error
r = json.dumps(info['test'])
loaded_r = json.loads(r)
and when try extract Application_name from it:
loaded_r['Application name']
or Source
loaded_r['Source']
i'm getting TypeError: string indices must be integers
as suggested by duplicate link tried also print (loaded_r['Source'][0])
and print(str(r['Source']))
but the same
Message body example (used segments to leave only first some lines to remove duplicates):
Source: example_host_1
Timestamp: 2019-01-22T00:00:43.901Z
Message: null
For instructions please see: wiki_link
Application name: example.api
Source: example_host_2
Timestamp: 2019-01-23T07:42:12.649Z
Message: HTTP "GET" "/api/endpoint/groups" responded 500 in 7795.6441 ms
Application name: service.API
Source: example_host_2
Timestamp: 2019-01-23T07:42:12.646Z
Message: Unhandled exception
For instructions please see: example_wiki_link
Dictionary stored in info
variable
{'test': '\r\nApplication name: app.service\r\nSource: example_host_1\r\nTimestamp: 2019-01-22T00:00:43.901Z\r\nMessage:'}
{'test': '\r\nApplication name: app.API\r\nSource: adc266f53205\r\nTimestamp: 2019-01-23T07:42:12.649Z\r\nMessage: HTTP"GET" "/api/endpoint/groups" responded 500'}
我认为loaded_r
是一个字符串而不是字典。
I think i'm good now, made some "mumbo-jumbo" but it works, converted dictionary to string and then used regex.Thanks everyone
res = ','.join([','.join(i) for i in info.items()])
x = res.replace('test,','')
regex1=r'Application name:\s*(.+?)\s+Source'
regex2=r'Source:\s*(.+?)\s+Timestamp:'
regex3 = r'(?<!^)Message:\s*.*'
a = re.findall(regex1 ,x)
b = re.findall(regex2 ,x)
c = re.findall(regex3, x)
print (a, b, c)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.