Im trying to compare if a value from jsonA(deployed_devices) exists in jsonB(assigned_components) and merge them into one new json Object. The goal is to iterate over every asset_it in the deployed_devices json and check if and where the asset_id matches witch the id in assigned_components[data][rows] and generate a new JSON. Heres my current code which generates a new json but leaves the ‘Components’ in the new JSON(matched_devices) completely empty:
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
Those are the JSON to work with (cropped the output a bit for better overview):
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 ...
]
}
}
]
2
Answers
I managed to get it working with the following code:
Ok let’s solve this issue:
Having said that, here’s the solution:
This function will make this variable. I hope this is your goal.