Home > OS >  Fetch the Json for a particular key value
Fetch the Json for a particular key value

Time:01-03

for an input json

[{
        "Name": "John",
        "Age": "23",
        "Des": "SE"
    },
    {
        "Name": "Rai",
        "Age": "33",
        "Des": "SSE"
    },
    {
        "Name": "James",
        "Age": "42",
        "Des": "SE"
    }
]

I want to filter out the json data where only "Des":"SE" is true

required output

[{
        "Name": "John",
        "Age": "23"
    },
    {
        "Name": "James",
        "Age": "42"
    }
]

CodePudding user response:

A list comprehension should do it:

out = [{'Name':d['Name'], 'Age':d['Age']} for d in lst if d['Des']=='SE']

Another way:

out = [d for d in lst if d.pop('Des')=='SE']

Output:

[{'Name': 'John', 'Age': '23'}, {'Name': 'James', 'Age': '42'}]

CodePudding user response:

To make it more dynamic if each json has more elements:

import json
input_str = '[{"Name": "John", "Age": "23", "Des": "SE"}, {"Name": "Rai", "Age": "33", "Des": "SSE"}, {"Name": "James", "Age": "42", "Des": "SE"}]'
input_list = json.loads(input_str)

# If you already converted to a list of dicts, then you don't need the above
# Using pop here removes the key you are using to filter
output = [each for each in input_list if each.pop("Des") == "SE"]

CodePudding user response:

using the json module, you can load a file using loads or a string using load. From there, it acts as a normal python list of dictionaries which you can iterate over and check the keys of. From there, you simply create a new list of dictionaries that match your desired pattern and remove the key you are no longer using. Example:

import json


jsonString = """[{
        "Name": "John",
        "Age": "23",
        "Des": "SE"
    },
    {
        "Name": "Rai",
        "Age": "33",
        "Des": "SSE"
    },
    {
        "Name": "James",
        "Age": "42",
        "Des": "SE"
    }
]"""
jsonList = json.loads(jsonString)


filteredList = []
def CheckDes(dataDict: dict):
    if dataDict['Des'] == 'SE':
        dataDict.pop('Des')
        filteredList.append(dataDict)



print(jsonList)
"""
[
    {
        'Name': 'John', 
        'Age': '23', 
        'Des': 'SE'
    },
    {
        'Name': 'Rai', 
        'Age': '33', 
        'Des': 'SSE'
    },
    {
        'Name': 'James', 
        'Age': '42', 
        'Des': 'SE'
    }
]"""

[CheckDes(dataDict) for dataDict in jsonList]

print(filteredList)
"""[
    {   
        'Name': 'John', 
        'Age': '23'
    },
    {   
        'Name': 'James', 
        'Age': '42'
    }
]
"""
  • Related