我有一个包含多个字典结构的 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"
}
请告诉我如何编码。任何帮助/建议表示赞赏。
答案 0 :(得分:0)
要将 json 字符串转换为 python dict(或在本例中为 dict 列表),您可以使用 json.loads
。然后,遍历字典列表,查看 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)