【问题标题】:Parse Response via Python通过 Python 解析响应
【发布时间】:2021-10-29 02:33:36
【问题描述】:

我想请你帮忙。 我有以下输出:

{
   'ActivationId': '24d8bac5-b849-42b2-b996-ca15fd829826', 
   'ActivationCode': 'jLu1oMmFGhZ/HQFGPr9P',
   'ResponseMetadata': {
      'RequestId': '7fc216f9-4c62-4b49-a17d-57c865f439ec', 
      'HTTPStatusCode': 200, 
      'HTTPHeaders': {
         'server': 'Server', 
         'date': 'Mon, 30 Aug 2021 09:58:39 GMT',
         'content-type': 'application/x-amz-json-1.1', 
         'content-length': '95', 
         'connection': 'keep-alive', 
         'x-amzn-requestid': '7fc216f9-4c62-4b49-a17d-57c865f439ec'
      }, 
      'RetryAttempts': 0
   }
}

我需要解析这样的输出,以便只获得 2 个值并将它们用作进一步处理的变量:

id=24d8bac5-b849-42b2-b996-ca15fd829826
code=jLu1oMmFGhZ/HQFGPr9P

请问如何通过 Python 实现它?

非常感谢提前 彼得

【问题讨论】:

    标签: python json python-3.x parsing


    【解决方案1】:

    只需执行以下操作:-

    output_dict = {'ActivationId': '24d8bac5-b849-42b2-b996-ca15fd829826', 'ActivationCode': 'jLu1oMmFGhZ/HQFGPr9P', 'ResponseMetadata': {'RequestId': '7fc216f9-4c62-4b49-a17d-57c865f439ec', 'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'Server', 'date': 'Mon, 30 Aug 2021 09:58:39 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '95', 'connection': 'keep-alive', 'x-amzn-requestid': '7fc216f9-4c62-4b49-a17d-57c865f439ec'}, 'RetryAttempts': 0}}
    
    id = output_dict['ActivationId']
    code = output_dict['ActivationCode']
    
    

    如果您有多个此类响应,则可以循环使用此代码。

    【讨论】:

      【解决方案2】:

      你的意思是:

      response = {...}
      id = response.get("ActivationID")
      code = response.get("ActivationCode")
      

      或者如果是原始的json,那么:

      import json
      raw_json = '{...}'
      response = json.loads(raw_json)
      id = response.get("ActivationID")
      code = response.get("ActivationCode")
      

      【讨论】:

      • 谢谢!这对我帮助很大!
      • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
      【解决方案3】:

      我想这可能对你有帮助

      for key,val in var.items():
          if 'ActivationId' in key or 'ActivationCode' in key:
              print(key,val)
      

      结果

      ActivationId 24d8bac5-b849-42b2-b996-ca15fd829826
      ActivationCode jLu1oMmFGhZ/HQFGPr9P
      

      【讨论】:

        猜你喜欢
        • 2021-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多