[英]How to find a dictionary based on a value from a list of dict?
我有一個 json 文件,其中包含多個字典結構,如下所示。
[
{
"advisories": [
],
"affected_packages": [
],
"bugzilla": "1944167",
"bugzilla_description": "CVE-2021-3472 xorg-x11-server: XChangeFeedbackControl integer underflow leads to privilege escalation",
"CVE": "CVE-2021-3472",
"cvss_score": null,
"cvss_scoring_vector": null,
"cvss3_score": "7.8",
"cvss3_scoring_vector": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H",
"CWE": "CWE-191",
"public_date": "2021-04-13T14:00:00Z",
"resource_url": "https://access.redhat.com/hydra/rest/securitydata/cve/CVE-2021-3472.json",
"severity": "important"
},
{
"advisories": [
],
"affected_packages": [
],
"bugzilla": "1948726",
"bugzilla_description": "CVE-2020-7924 mongodb: sslAllowInvalidHostnames bypass ssl/tls server certification validation entirely",
"CVE": "CVE-2020-7924",
"cvss_score": null,
"cvss_scoring_vector": null,
"cvss3_score": "5.1",
"cvss3_scoring_vector": "CVSS:3.1/AV:L/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N",
"CWE": "CWE-295",
"public_date": "2021-04-12T00:00:00Z",
"resource_url": "https://access.redhat.com/hydra/rest/securitydata/cve/CVE-2020-7924.json",
"severity": "moderate"
}
]
現在我想讀取 json 文件並根據值獲取字典內容。 假設我的值是CVE-2020-7924
,那么我需要將完整的字典提取到變量或某個文件中。
例如,如果我搜索CVE-2020-7924
,則結果應如下所示:
{
"advisories": [
],
"affected_packages": [
],
"bugzilla": "1948726",
"bugzilla_description": "CVE-2020-7924 mongodb: sslAllowInvalidHostnames bypass ssl/tls server certification validation entirely",
"CVE": "CVE-2020-7924",
"cvss_score": null,
"cvss_scoring_vector": null,
"cvss3_score": "5.1",
"cvss3_scoring_vector": "CVSS:3.1/AV:L/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N",
"CWE": "CWE-295",
"public_date": "2021-04-12T00:00:00Z",
"resource_url": "https://access.redhat.com/hydra/rest/securitydata/cve/CVE-2020-7924.json",
"severity": "moderate"
}
請讓我知道如何編碼。 任何幫助/建議表示贊賞。
要將 json 字符串轉換為 python 字典(或在本例中為字典列表),您可以使用json.loads
。 然后,遍歷 dicts 列表,查看dict["CVE"]
是否等於您的值,如果是,請將其設置為某個變量。 如果您想將該變量導出到可以寫入文件的 json 字符串,請使用json.dumps
。 例子:
import json
CVE_voi = "CVE-2020-7924" # CVE_value_of_interest
inf = open("/path/to/file/containing/data.json", "r")
instr = inf.read()
print(len(instr)) # prints length of json str
print(instr[:100]) # prints first 99 chars of json str
inf.close()
dictlist = json.loads(instr)
for d in dictlist:
if d["CVE"] == CVE_voi:
doi = d # copy dict_of_interest in a variable
outf = open("/path/to/outputfile.json", "w")
outstr = json.dumps(doi)
outf.write(outstr)
outf.close()
break
else: # print a message when no dict with the given CVE value was found
print("no dict containing CVE %s could be found" % CVE_voi)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.