Skip to content
Advertisement

How to replace json value with list of items based on the key

How do I replace the json_object’s blookup with blookup_values based on the ID’s in the json blookup. I tried the below code by removing the ID’s which are not present in the json_object[‘blookup’]. The below code doesn’t work. Could anyone please help.

blookup_values = [
{
    "id":"123",
    "name":"abc",
    "date":"somedate",
    "time":"sometime"
},
{
    "id":"456",
    "name":"def",
    "date":"somedate",
    "time":"sometime"
},
{
    "id":"789",
    "name":"ghi",
    "date":"somedate",
    "time":"sometime"
},
{
    "id":"9999",
    "name":"mmmmmm",
    "date":"somedate",
    "time":"sometime"
},
{
    "id":"8888",
    "name":"nnnnnn",
    "date":"somedate",
    "time":"sometime"
}
]

json_object = {
"id":"id_value",
"blookup": [{
    "id":"123",
    "type":"dddd"
},
    {
        "id":"456",
        "type":"eeeee"
    }
]
}

Code

result = [obj for obj in blookup_values if obj['id'] != json_object['blookup']]

Expected result

result = {
"id":"id_value",
"blookup": [{
    "id":"123",
    "name":"abc",
    "date":"somedate",
    "time":"sometime"
},
    {
        "id":"456",
        "name":"def",
        "date":"somedate",
        "time":"sometime"
    }
]
}

Advertisement

Answer

You have to get the id key from the json_object dictionaries:

result = [obj for obj in blookup_values if obj['id'] in [i["id"] for i in json_object['blookup']]]
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement