如何使用Python比较2个json文件并合并为一个

问题描述 投票:0回答:1

我试图比较 jsonA(deployed_devices) 中的值是否存在于 jsonB(signed_components) 中,并将它们合并到一个新的 json 对象中。目标是迭代已部署的设备 json 中的每个 asset_it,并检查 asset_id 是否以及在何处与分配的组件 [数据] [行] 中的 id 匹配,并生成新的 JSON。这是我当前的代码,它生成一个新的 json,但将新 JSON(matched_devices) 中的“组件”完全留空:

def match_device_components(assigned_components, deployed_devices):
    matched_devices = []

    for component_entry in assigned_components:
        for component_name, component_data in component_entry.items():
            component_rows = component_data.get('data', {}).get('rows', [])

            assigned_component_ids = {component["id"] for component in component_rows}

            for device in deployed_devices:
                matched_components = []

                for component in component_rows:
                    if component["id"] == device["asset_id"]:
                        matched_components.append(component["name"])

                matched_device = {
                    "model_name": device["model_name"],
                    "asset_tag": device["asset_tag"],
                    "asset_id": device["asset_id"],
                    "components": matched_components
                }

                matched_devices.append(matched_device)

    return matched_devices

这些是要使用的 JSON(稍微裁剪输出以便更好地概览):

deployed_devices = [
    {
        "model_name": "RACK/BOX",
        "asset_tag": "X-0043",
        "asset_id": "234"
    },
    .... more devices ... 
]

assigned_components = [
   {
      "Camera":{
         "id":70,
         "name":"Camera",
         "user_can_checkout":1,
         "available_actions":{
            "checkout":true,
            "checkin":true,
            "update":true,
            "delete":true
         }
      },
      "data":{
         "total":52,
         "rows":[
            {
               "assigned_pivot_id":710,
               "id":133,
               "name":"BOX 25x17x21",
               "qty":2,
               "note":"",
               "type":"asset",
               "created_at":{
                  "datetime":"2024-01-15 11:59:06",
                  "formatted":"15.01.2024 11:59"
               },
               "available_actions":{
                  "checkin":true
               }
            },
            ... many more rows ... 
         ]
      }
   },
   {
      "LED":{
         "id":69,
         "name":"LED ",
         "user_can_checkout":1,
         "available_actions":{
            "checkout":true,
            "checkin":true,
            "update":true,
            "delete":true
         }
      },
      "data":{
         "total":10,
         "rows":[
            {
               "assigned_pivot_id":823,
               "id":57,
               "name":"BOX 25x17x21",
               "qty":1,
               "note":"None",
               "type":"asset",
               "created_at":{
                  "datetime":"2024-01-22 10:50:34",
                  "formatted":"22.01.2024 10:50"
               },
               "available_actions":{
                  "checkin":true
               }
            },
            ... many more rows ... 
         ]
      }
   }
]
python json python-3.x comparison
1个回答
0
投票

好吧,让我们解决这个问题:

  1. 您的代码有点混乱,因为您的 for 循环实际上没有给出任何结果,所以我建议您“打印”变量以了解您在做什么;
  2. 您正在谈论 JSON 格式,因此管理 JSON 数据库的更好方法是使用专用的 python 包;
  3. 你的问题有点不清楚。

话虽如此,解决方案如下:

def match_device_components(assigned_components, deployed_devices):
   matched_devices = []
   matched_components = []

   for components in json.loads(json.dumps(assigned_components)):
       c_id=components['data']['rows'][0]['id']
       # print(c_id)

   for device in json.loads(json.dumps(deployed_devices)):
       d_id=device['asset_id']
       # print(d_id)

   if int(c_id) == int(d_id):
       matched_components.append(components['data']['rows'][0]['name'])

       matched_device = {
           "model_name": device["model_name"],
           "asset_tag": device["asset_tag"],
           "asset_id": device["asset_id"],
           "components": matched_components
       }

       matched_devices.append(matched_device)  
       print(json.dumps(matched_device, indent=4))

if __name__ == '__main__':
   match_device_components(assigned_components, deployed_devices)

该函数将使该变量。我希望这是你的目标。

{
    "model_name": "RACK/BOX",
    "asset_tag": "X-0043",
    "asset_id": "57",
    "components": [
        "BOX 25x17x21"
    ]
}
© www.soinside.com 2019 - 2024. All rights reserved.