简体   繁体   English

我需要使用 python 从字符串中提取字典

[英]I need to extract the dictionary from the string using python

''[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" }我只想要 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" :“”,“时区”:“UTC”}

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)

Try尝试

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

Now you can use res dict to access it.现在您可以使用 res dict 来访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM