[英]How to get complete dictionary data from a JSON file based on a value
我有一个 json 文件,我将阅读该文件并根据 xyz 详细信息创建 excel 报告。 下面是示例 json 文件,我将使用它来提取包含多个字典格式数据的信息。
现在我的要求是一个一个地获取 xyz 值,并基于它使用某些字段创建一个报告。 下面是我正在读取文件并基于关键填充结果的代码的小片段。 我从文件中读取后引用的数据。
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()
我非常坚持如何在def read_f(data):
中编码,以便它读取dat.json
并基于值即data
,为所有必需的数据一一获取字典结构中定义的详细信息并按定义填充在我的代码中的pop_ws
下。
def read_f(data):
data
的数据将是一个动态值,基于它我需要过滤具有针对键定义的值(存储在data
中)的字典,然后将整个字典提取到另一个 json 文件中。
对此的任何建议将不胜感激。
获得 json object 后,您可以使用以下键访问每个值:
print(json_obj["key"]) #prints the json value for that key
在你的情况下
print(wrk["CVE"]) # prints CVE-2020-25624
使用 json package 加载 json 格式数据如下:
# 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()
我从这个链接得到这个,现在你可以从文件中得到 dict。
接下来,您可以使用特定值过滤字典,如下所示。 如果字典包含其中一个值,则应使用 filter() 内置 function 和返回 True 的 function。
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))
您应该使用字典作为第二个元素。
filter_cards(deck, {'CVE': 'moderate'})
希望这对您的情况有所帮助。
谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.