【问题标题】:Python - How print inner keys of json in a for loop?Python - 如何在 for 循环中打印 json 的内部键?
【发布时间】:2020-11-20 12:42:31
【问题描述】:

我有一个这样的 json 文件

[
    {
        "analysis_start_time": "2020-10-24T17:29:00+00:00",
        "av_detect": 67,
        "certificates": [],
        "classification_tags": [
            "apt",
            "apt28",
            "apt29",
            "cozer",
            "cozybear",
            "cozycar",
            "cozyduke",
            "downloader",
            "dukes",
            "euroapt",
            "exploit",
            "fancybear",
            "group-4127",
            "group100",
            "group74",
            "hammertoss",
            "infostealer",
            "irontwilight",
            "minidionis",
            "officemonkeys",
            "pawnstorm",
            "qakbot",
            "seaduke",
            "sednit",
            "sofacy",
            "strontium",
            "swallowtail",
            "tag_0700",
            "tg-4127",
            "thedukes",
            "tsarteam",
            "zemot"
        ],
        "mitre_attcks": [
            {
                "attck_id": "T1046",
                "attck_id_wiki": "https://attack.mitre.org/techniques/T1046",
                "informative_identifiers": [],
                "informative_identifiers_count": 0,
                "malicious_identifiers": [],
                "malicious_identifiers_count": 0,
                "suspicious_identifiers": [],
                "suspicious_identifiers_count": 1,
                "tactic": "Discovery",
                "technique": "Network Service Scanning"
            },
            {
                "attck_id": "T1016",
                "attck_id_wiki": "https://attack.mitre.org/techniques/T1016",
                "informative_identifiers": [],
                "informative_identifiers_count": 0,
                "malicious_identifiers": [],
                "malicious_identifiers_count": 1,
                "suspicious_identifiers": [],
                "suspicious_identifiers_count": 0,
                "tactic": "Discovery",
                "technique": "System Network Configuration Discovery"
            }
        ],

}

{
        "analysis_start_time": "2020-07-10T14:39:28+00:00",
        "av_detect": 67,
        "certificates": [],
        "classification_tags": [],
        "compromised_hosts": [],
        "domains": [],
        "environment_description": "Static Analysis",
        "environment_id": null,
        "error_origin": null,
        "error_type": null,
        "extracted_files": [],
        "file_metadata": null,
        "hosts": [],
        "imphash": null,
        "interesting": false,
        "job_id": null,
        "md5": "77e7fb6b56c3ece4ef4e93b6dc608be0",
        "mitre_attcks": [],
        "processes": [],
        "sha1": "f46f84e53263a33e266aae520cb2c1bd0a73354e",
        "sha256": "5130f600cd9a9cdc82d4bad938b20cbd2f699aadb76e7f3f1a93602330d9997d",
        "sha512": "fb35607e7b1279a404927f4fb8b714aa766872d66a187af9a89955143b21785611d6073bfaf28686b4d93dba1756073b802afba82ff0e8a1272dd853ab88924a",
        "size": 23552,
        "ssdeep": null,
        "state": "SUCCESS",
        "submissions": [
            {
                "created_at": "2020-07-10T14:39:28+00:00",
                "filename": "file",
                "submission_id": "5f087da0ef7c213b097953e2",
                "url": null
            }
        ],
        "submit_name": "file",
        "tags": [],
        "target_url": null,
        "threat_level": 2,
        "threat_score": null,
        "total_network_connections": 0,
        "total_processes": 0,
        "total_signatures": 0,
        "type": "PE32+ executable (console) x86-64 (stripped to external PDB), for MS Windows",
        "type_short": [
            "peexe",
            "64bits",
            "executable"
        ],
        "url_analysis": false,
        "verdict": "malicious",
        "vx_family": "Application.Pup"
    },

and so on (total 4 but they could be more)

我的代码是:

for i in jsonOut:

                    try:
                         print('- Start time '+i['analysis_start_time']+'\n')
                    except:
                         print('\n')
                         
                    try:
                         print('- Detetction: '+str(i['av_detect'])+'%\n')
                    except:
                        print('\n')
                    try:
                        
                         print('- Signatures: '+str(i['total_signatures'])+'\n')
                    except:
                        print('\n')
                        
                    try:
                         print('- Threat Level: '+str(i['threat_score'])+'\n')
                    except:
                        print('\n')
                        
                    try:
                         print('- Verdict: '+str(i['verdict'])+'\n')
                    except:
                        print('\n')
                    
                    try:
                        print('- Suspicious id: '+str(i['mitre_attcks']['suspicious_identifiers_count'])+'\n')
                    except:
                        print('\n')
                                        
                    try:
                       print('- Maliciuos id: '+str(i['mitre_attcks']['malicious_identifiers_count'])+'\n\n')
                       print('-----------------------------------------')                               
                    except:
                                        print('\n')

我的输出是,但没有关于“mitre_attcks”的信息

  • 开始时间 2020-10-24T17:29:00+00:00

  • 检测:67%

  • 签名:5

  • 威胁等级:99

  • 判决:恶意

  • 开始时间 2020-07-10T14:39:28+00:00

  • 检测:67%

  • 签名:0

  • 威胁级别:无

  • 判决:恶意

  • 开始时间 2019-01-11T20:48:12+00:00

  • 检测:67%

  • 签名:12

  • 威胁等级:100

  • 判决:恶意

  • 开始时间 2015-10-09T00:57:40+00:00

  • 检测:67%

  • 签名:7

  • 威胁等级:16

  • 判决:可疑

我尝试在第一个 ---> for j in i['mitre_attcks'] 之后放置另一个 for 循环: 但不起作用。 我该如何解决这个问题? 谢谢

【问题讨论】:

  • 仅使用except: 将捕获所有错误。这通常不是你想要的。看起来你在 try 块中有一个 KeyError,因为 i['mitre_attcks'] 是一个列表,在访问每个字段之前需要循环或索引。

标签: python json for-loop


【解决方案1】:

问题是你没有遍历mitre_attcks数组,你也不一定需要使用try-except块来检查字典中是否存在键,你可以使用@987654323 @ 运算符和一个 if

这可能是你的问题的解决方案,你只需要将"test.json"路径调整为你自己的JSON文件的实际路径即可:

import json

with open("test.json") as json_file:
    analysis_data = json.load(json_file)


report = ""
for analysis in analysis_data:

    if "analysis_start_time" in analysis:
        report += "- Start time: " + analysis["analysis_start_time"] + "\n\n"
    if "av_detect" in analysis:
        report += "- Detection: " + str(analysis["av_detect"]) + "\n\n"
    if "total_signatures" in analysis:
        report += "- Signatures: " + str(analysis["total_signatures"]) + "\n\n"
    if "threat_score" in analysis:
        report += "- Threat Level: " + str(analysis["threat_score"]) + "\n\n"
    if "verdict" in analysis:
        report += "- Verdict: " + str(analysis["verdict"]) + "\n\n"
    if "mitre_attcks" in analysis:
        report += "- Mitre Attacks: \n\n"
        for attack in analysis["mitre_attcks"]:
            if "suspicious_identifiers_count" in attack:
                report += (
                    "\t- Suspicious id: "
                    + str(attack["suspicious_identifiers_count"])
                    + "\n\n"
                )
            if "malicious_identifiers_count" in attack:
                report += (
                    "\t- Maliciuos id: "
                    + str(attack["malicious_identifiers_count"])
                    + "\n\n"
                )
            report += "\t" + "*" * 20 + "\n\n"

    report += "-" * 30 + "\n\n"

print(report)

输出:

- Start time: 2020-10-24T17:29:00+00:00

- Detection: 67%

- Mitre Attacks: 

        - Suspicious id: 1

        - Maliciuos id: 0

        ********************

        - Suspicious id: 0

        - Maliciuos id: 1

        ********************

------------------------------

- Start time: 2020-07-10T14:39:28+00:00

- Detection: 67%

- Signatures: 0

- Threat Level: None

- Verdict: malicious

- Mitre Attacks: 

------------------------------

【讨论】:

    猜你喜欢
    • 2021-09-24
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 2018-07-05
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多