【问题标题】:Python Adding UUIDs to list to be appended to JSON/Dict objectPython将UUID添加到要附加到JSON/Dict对象的列表中
【发布时间】:2021-12-30 10:47:07
【问题描述】:

到目前为止,我有以下代码:

for endpoint in endpoints:
   post_aga = APINSRRequestsRouter()
   response_obj_aga = post_aga.send_aga_post_request(endpoint)

   if response_obj_aga:
      if response_obj_aga[0] == "201":
         id = response_obj_aga[1]["ACK"]["id"]

         #dictionary with list code here

response_obj_aga 是一个列表对象,包含一个字符串和一个 json 对象,例如:

['200', {'ACK': {'message': 'something happened', 'id': '319711da-20fd-4c94-bf8b-04735b435dd1'}}]

我想要做的是每次我得到一个包含 id 的 response_obj_aga 对象时,我想将该 id 附加到字典中的列表中,以便我可以将它作为 JSON 对象保存在我的数据库中。因此,假设我期待 3 个单独的响应,并拥有以下数据:

['200', {'ACK': {'message': 'something happened', 'id': '17d362ae-a796-40fd-a1c3-0ff64e6f62e0'}}]

['200', {'ACK': {'message': 'something happened', 'id': '54e63ab8-aa1b-4d6f-a570-6ee7e52e2318'}}]

['200', {'ACK': {'message': 'something happened', 'id': 'b0a8ad20-b3e6-4100-963e-0f5e7f7e51f5'}}]

我想在循环结束时得到的是这样的:

{
  "ids": [
        "17d362ae-a796-40fd-a1c3-0ff64e6f62e0",
        "54e63ab8-aa1b-4d6f-a570-6ee7e52e2318",
        "b0a8ad20-b3e6-4100-963e-0f5e7f7e51f5"
  ]
}

最有效的方法是什么?

【问题讨论】:

    标签: json python-3.x list dictionary


    【解决方案1】:

    创建一个模板对象并在读取响应时将 ID 附加到它。

    工作示例:

    import json
    
    responses = [['200', {'ACK': {'message': 'something happened', 'id': '17d362ae-a796-40fd-a1c3-0ff64e6f62e0'}}],
                 ['200', {'ACK': {'message': 'something happened', 'id': '54e63ab8-aa1b-4d6f-a570-6ee7e52e2318'}}],
                 ['200', {'ACK': {'message': 'something happened', 'id': 'b0a8ad20-b3e6-4100-963e-0f5e7f7e51f5'}}]]
    
    result = {'ids':[]}
    
    for response in responses:
        result['ids'].append(response[1]['ACK']['id'])
    
    print(json.dumps(result, indent=2))
    

    输出:

    {
      "ids": [
        "17d362ae-a796-40fd-a1c3-0ff64e6f62e0",
        "54e63ab8-aa1b-4d6f-a570-6ee7e52e2318",
        "b0a8ad20-b3e6-4100-963e-0f5e7f7e51f5"
      ]
    }
    

    你的代码应该是什么样子:

    result = {'ids':[]}
    
    for endpoint in endpoints:
       post_aga = APINSRRequestsRouter()
       response_obj_aga = post_aga.send_aga_post_request(endpoint)
    
       if response_obj_aga:
          if response_obj_aga[0] == "201":
             id_ = response_obj_aga[1]["ACK"]["id"]
    
             result['ids'].append(id_)
    

    注意:id 是 Python 中的内置函数,不应用作变量名。

    【讨论】:

      猜你喜欢
      • 2017-11-17
      • 2020-12-03
      • 1970-01-01
      • 2013-08-07
      • 2017-11-30
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      相关资源
      最近更新 更多