python-3.x 从字符串中提取字典

iyfjxgzm  于 2022-12-24  发布在  Python
关注(0)|答案(2)|浏览(112)
'''[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"
}'''

我该如何转换这个字符串,使其内部只包含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"
}
kh212irz

kh212irz1#

你可以这样做得到字符串形式

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

如果你想把它作为一个dict对象

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)
t1rydlwq

t1rydlwq2#

试试看
res = json.loads(字符串变量)打印(res)
现在您可以使用resdict来访问它。

相关问题