PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 25, 2022

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

 July 25, 2022     json, python     No comments   

Issue

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"
    }
]
}

Solution

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']]]


Answered By - JacobIRR
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing