How to filtering out json object contain certain key in FLASK?

Question:

I have a JSON file :

    {
           "id":"xyz",
           "word":"this is word",
           "formats":[
              {
                 "formatId":"xz99",
                 "pengeluaran":"pengeluaran_1",
                 
              },
              {
                 "formatId":"xy100",
                 "pengeluaran":"pengeluaran_2",
                 
              },
              {
                 
                 "ukuran":451563,
                 "formatId":"xy101",
                 "pengeluaran":"pengeluaran_1",
             
            },
        }

in my python.py files, i want to filtering out the JSON object only contain "ukuran" as a key , my expected to getting result like this :

    {
           "id":"xyz",
           "word":"this is word",
           "formats":[
              {
                 
                 "ukuran":451563,
                 "formatId":"xy101",
                 "pengeluaran":"pengeluaran_1",
             
            },
        }

this my python.py code :

    def extractJson(appData):    
        appData = json.loads(output)
        
        //list comprehension to filter out only JSON object contain "ukuran"?

        print(appData)

Thanks in advance.

Asked By: warstha

||

Answers:

It could look something like this:

This example uses list comprehension to filter out the correct format by checking to see if the format contains the key "ukuran", and then assigning the filtered list back "formats" key for the object.

def extractJson(output):    
    appData = json.loads(output)
    appData["formats"] = [
       format for format in appData["formats"] if "ukuran" in format
    ]
    print(appData)
    return appData
Answered By: Alexander
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.