我试图比较 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 ...
]
}
}
]
好吧,让我们解决这个问题:
话虽如此,解决方案如下:
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"
]
}