How to get complete dictionary data from a JSON file based on a value

Viewed 332

I have a json file, which I will read and based on the xyz details will create excel report. Below is the sample json file I will use to extract the information which holds data in format of multiple dictionaries.

Now my requirement is to fetch xyz value one by one and based on it using certain field create a report. Below is the small snippet of the code where I am reading the file and based on key populating results. The data I am referencing after reading it from a file.

def pop_ws(dictionary,ws):
  r=1
  count=1
  for k,v in dictionary.items():
   offs=len(v['current'])
   ws.cell(row=r+1,column=1).value = k
   ws.cell(row=r+1,column=4).value = v['abc']
   ws.cell(row=r+1,column=5).value = v['def']
   wrk=read_cves(k)
   count +=1
   if wrk !='SAT':
      ws.cell(row=r+1,column=7).value =k
      ws.cell(row=r+1,column=8).value =tmp1['public_date']
      if 'cvss' in list(tmp1.keys()):
      .
      .
      .
      

def read_f(data):
 with open(dat.json) as f:
    wrk = f.read()

I am pretty much stuck on how to code in def read_f(data):, so that it read dat.json and based on value i.e data, fetch details defined as in dictionary structure one by one for all the required data and populate as defined under pop_ws in my code.

The data in def read_f(data): will be a dynamic value and based on it I need to filter the dictionary which have value (stored in data) defined against a key and then extract the whole dictionary into another json file.

Any suggestion on this will be appreciated.

2 Answers

Once you get your json object, you can access each value using the key like so:

print(json_obj["key"]) #prints the json value for that key

In your case

print(wrk["CVE"]) # prints CVE-2020-25624

Use json package to load json format data like below:

# Python program to read
# json file


import json

# Opening JSON file
f = open('data.json',)

# returns JSON object as
# a dictionary
data = json.load(f)

# Iterating through the json
# list
for i in data['emp_details']:
    print(i)

# Closing file
f.close()

I got this from this link, now you can get dict from the file.

Next you can just filter the dict with specific value like below. You should use filter() built-in function, with a function that returns True, if the dictionary contains one of the values.

def filter_func(dic, filterdic):
    for k,v in filterdic.items():
        if k == 'items':
            if any(elemv in dic[k] for elemv in v):
                return True
        elif v == dic[k]:
            return True
    return False

def filter_cards(deck, filterdic):
    return list(filter(lambda dic, filterdic=filterdic: filter_func(dic, filterdic) , deck))

You should use a dictionary as the second element.

filter_cards(deck, {'CVE': 'moderate'})

Hopefully, this could helpful for your situation.

Thanks.

Related