Home > OS >  I need to extract the dictionary from the string using python
I need to extract the dictionary from the string using python

Time:12-21

''[ERROR] 2020-10-01T04:46:37.sdfsdqs889dgsdg9dgdf {
"correlation_id": "asdfsdf-dsfasdfa-adfadsf-asdf",
"invocation_timestamp": null,
"invoked_component": "lambda",
"invoker_agent": null,
"message": {
"errorMessage": "Unauthorized",
"statusCode": 401
},
"message_type": "ERROR",
"original_source_app": "",
"response_timestamp": "2020-10-01 04:46:37.121436",
"status": 401,
"target_idp_application": "",
"timezone": "UTC"
}'''

I want only dict { "correlation_id": "asdfsdf-dsfasdfa-adfadsf-asdf", "invocation_timestamp": null, "invoked_component": "lambda", "invoker_agent": null, "message": { "errorMessage": "Unauthorized", "statusCode": 401 }, "message_type": "ERROR", "original_source_app": "", "response_timestamp": "2020-10-01 04:46:37.121436", "status": 401, "target_idp_application": "", "timezone": "UTC" }

CodePudding user response:

You could do something like this to get the string form

test = '''[ERROR] 2020-10-01T04:46:37.sdfsdqs889dgsdg9dgdf {
"correlation_id": "asdfsdf-dsfasdfa-adfadsf-asdf",
"invocation_timestamp": null,
"invoked_component": "lambda",
"invoker_agent": null,
"message": {
"errorMessage": "Unauthorized",
"statusCode": 401
},
"message_type": "ERROR",
"original_source_app": "",
"response_timestamp": "2020-10-01 04:46:37.121436",
"status": 401,
"target_idp_application": "",
"timezone": "UTC"
}'''

print(test[test.find('{'):]) # find the first '{' and discard all characters before that index in the string

and you could do this if you want it as a dict object

import json
dict_form = json.loads(test[test.find('{'):]) # same as before now sending it to json.loads which converts a string to a dict object (as most requests are sent as a string)
print(dict_form)

CodePudding user response:

Try

res = json.loads(string_var) print(res)

Now you can use res dict to access it.

  • Related