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

f45qwnt8  于 2022-12-21  发布在  Python
关注(0)|答案(2)|浏览(154)
''[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 {“相关ID”:“asdfsdf-dsfasdfa-adfadsf-asdf”,“调用时间戳”:空,“调用的组件”:“lambda”,“调用者代理”:空,“消息”:{“错误消息”:“未授权”,“状态代码”:401 },“消息类型”:“错误”,“原始源应用程序”:“",“响应时间戳”:“2020-10-01 04:46:37.121436”,“状态”:401,“目标_idp_应用程序”:“"、“时区”:“世界协调时”

34gzjxbg

34gzjxbg1#

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

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

yrwegjxp2#

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

相关问题