Home > front end >  Python 3.9 parse and filter json to have entire rows having specific keyword:value
Python 3.9 parse and filter json to have entire rows having specific keyword:value

Time:08-20

For a JSON file, on doing json.load its getting converted into list of dictionaries. sample rows are from list of dictionaries are as below: -

config_items_list = [{'hostname': '"abc2164"', 'Status': '"InUse"', 'source': '"excel"', 'port': '"[445]"', 'tech': '"Others"', 'ID': '"123456"'}, 
{'hostname': '"xyz2164"', 'Status': '"InUse"', 'source': '"web"', 'port': '"[123]"', 'tech': '"Others"', 'ID': '"456789"'}, 
{'hostname': '"pqr2164"', 'Status': '"NotInUse"', 'source': '"web"', 'port': '"[777]"', 'tech': '"Others"', 'ID': '"123456"'}]

Requirement is to parse this list of dictionaries and extract all rows having specific value in ID key. For example, 123456 (means two rows from above sample).

CodePudding user response:

try this solution it should solve your problem

def filter_json_with_id(config_items_list, id):
    items = []
    for item in config_items_list:
        if item['ID'] == id:
            items.append(item)
    return items

CodePudding user response:

select_id = '"123456"'
[d for d in config_items_list if d["ID"] == select_id]

will produce a list with those dictionaries that have given select_id as "ID" in config_items_list.

CodePudding user response:

By using below solution, it searches for the id_value even if the id_value is surrounded with any symbol or any other number/character as well: -

expectedResult = [d for d in config_items_list if "123456" in d['ApplicationInstanceID']]

  • Related