【问题标题】:Remove backslash from JSON string and print value of a key从 JSON 字符串中删除反斜杠并打印键的值
【发布时间】:2019-08-28 15:26:58
【问题描述】:

我正在尝试打印与 JSON 键值对的键对应的值。

使用 event_response 检索此 JSON 输出,如下所示。 我想打印 Effect 和 Action 的值,以便将其与正则表达式匹配并采取行动。我想获得没有反斜杠的值,以便与正则表达式匹配。 我尝试了替换,但没有成功

    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\":\"*\"}]}

【问题讨论】:

  • 打印event_response时得到什么值?
  • event_response 给出了问题中提到的输出,包括版本、声明等。
  • 哦,好的,请仔细检查一下,因为您的代码 sn-p 上有两次打印。
  • json.loads("event_response") 不可能工作。你的意思是json.loads(event_response) 没有引号?看起来该值也不是正确的 JSON —— 可能使用生成 JSON 的接口,或者找出应该使用哪种格式来解码。

标签: python json aws-lambda


【解决方案1】:

如果我理解正确,那么需要没有反斜杠的漂亮设计。您可以使用pprint 模块:

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

结果:

{'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'}

【讨论】:

  • 如何从上述 JSON 内容中获取键“Effect”和“Resource”。请帮忙。
  • 如上例:effect = json.loads(event_response)['Statement'][0]['Effect']resource = json.loads(event_response)['Statement'][0]['Resource']
  • 我只执行并添加了效果语句,但出现以下错误:- 期望用双引号括起来的属性名称:第 1 行第 2 列(字符 1):JSONDecodeError
  • 尝试将引号改为双引号: effect = json.loads(event_response)["Statement"][0]["Effect"]。尝试逐步执行effect = json.loads(event_response) - 没有错误? effect = json.loads(event_response)["Statement"] 及更多
  • 如果您的 json 不在event_response 中,而是在policy_details 中,则将代码更改为effect = json.loads(policy_details)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-28
  • 1970-01-01
  • 2021-09-14
相关资源
最近更新 更多