简体   繁体   中英

Remove backslash from JSON string and print value of a key

I am trying to print values corresponding to keys of JSON Key value pairs.

This JSON output is retrieved using event_response and it is shown below. I want to print values of Effect and Action so as to match it with a regular expression and take action. I want to get values without backslash so as to match with the regular expression. I tried replace but it didn't worked

    if "responseElements" in event['detail'].keys():
        event_response = \
            event["detail"]["responseElements"]["policy"]
        print(event_response) 
        policy_details = json.loads("event_response")
        print(policy_details)
{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"apigateway.amazonaws.com\"},\"Action\":[\"logs:CreateLogGroup\",\"logs:CreateLogStream\",\"logs:DescribeLogGroups\",\"logs:DescribeLogStreams\",\"logs:PutLogEvents\",\"logs:GetLogEvents\"],\"Resource\":\"*\"}]}

if I understand correctly, then beautiful design without backslash is required. You can use the pprint module:

import pprint
pprint.pprint(json.loads(event_response ))

result:

{'Statement': [{'Action': ['logs:CreateLogGroup',
                           'logs:CreateLogStream',
                           'logs:DescribeLogGroups',
                           'logs:DescribeLogStreams',
                           'logs:PutLogEvents',
                           'logs:GetLogEvents'],
                'Effect': 'Allow',
                'Principal': {'Service': 'apigateway.amazonaws.com'},
                'Resource': '*'}],
 'Version': '2012-10-17'}

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.

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