【问题标题】:get value of json.load [closed]获取 json.load 的值 [关闭]
【发布时间】:2021-01-24 13:52:57
【问题描述】:

嗨,我需要在 python 中获取 json 响应的值

{
"data": [{
        "incidentOriginId": "4f94d397a2611de4686778efe1188d90069685f94aab51afeb2b511985133067",
        "incidentClassPrimary": "MALWARE",
        "incidentClassSecondary": null,
        "startTime": "2020-12-23T08:00:51",
        "endTime": "2020-12-23T08:02:59",
        "lastUpdatedTime": "2020-12-24T09:26:45.309",
        "ip": "172.24.102.142",
        "risk": 8,
        "incidentState": null,
        "incidentDetails": "{\"id\":\"4f94d397a2611de4686778efe1188d90069685f94aab51afeb2b511985133067\",\"type\":\"incidents\",\"attributes\":{\"userFeedback\":\"NONE\",\"escalations\":[{\"@type\":\"cluster-label-change\",\"changeTime\":1608716795300,\"clusterLabel\":\"CSAL01\",\"category\":\"malware distribution\",\"riskCategory\":\"HIGH\"}],\"userNote\":null,\"confidence\":100,\"behindProxy\":false,\"flowCount\":7,\"incidentTypes\":[\"ADE\"],\"clusterLabels\":[\"CSAL01\"],\"stateChanges\":[],\"duration\":{\"startTime\":1608710451000,\"endTime\":1608710579000},\"incidentClass\":\"malware|malware distribution\",\"userFeedbackTimestamp\":null,\"eta\":false,\"blockedFlowCount\":0,\"reoccurring\":false,\"categoriesWithRisk\":[{\"category\":\"malware distribution\",\"riskCategory\":\"HIGH\"}],\"osType\":\"\",\"lastUpdatedTime\":1608802005309,\"risk\":8,\"state\":{\"stateType\":\"TRIAGE\"},\"persistent\":false,\"user\":{\"userName\":null,\"ipAddresses\":[{\"ipAddress\":\"172.24.102.142\",\"assignedFrom\":1608710451000,\"assignedTo\":1608710579000}]}},\"relationships\":{\"activities\":{\"links\":{\"self\":\"http://nginx/api/findings/v1/incidents/4f94d397a2611de4686778efe1188d90069685f94aab51afeb2b511985133067/relationships/activities\",\"related\":\"http://nginx/api/findings/v1/incidents/4f94d397a2611de4686778efe1188d90069685f94aab51afeb2b511985133067/activities\"}},\"clusters\":{\"links\":{\"self\":\"http://nginx/api/findings/v1/incidents/4f94d397a2611de4686778efe1188d90069685f94aab51afeb2b511985133067/relationships/clusters\",\"related\":\"http://nginx/api/findings/v1/incidents/4f94d397a2611de4686778efe1188d90069685f94aab51afeb2b511985133067/clusters\"}}},\"links\":{\"self\":\"http://nginx/api/findings/v1/incidents/4f94d397a2611de4686778efe1188d90069685f94aab51afeb2b511985133067\"}}"
    },
    {
        "incidentOriginId": "859a60b000b9beeb3323e58beab23de2091277ca0b661f36445db3a8e0ddd7a9",
        "incidentClassPrimary": "MALWARE",
        "incidentClassSecondary": null,
        "startTime": "2020-12-20T08:34:15",
        "endTime": "2020-12-29T10:18:09",
        "lastUpdatedTime": "2020-12-30T11:32:58.414",
        "ip": "172.24.102.142",
        "risk": 8,
        "incidentState": null,
        "incidentDetails": "{\"id\":\"859a60b000b9beeb3323e58beab23de2091277ca0b661f36445db3a8e0ddd7a9\",\"type\":\"incidents\",\"attributes\":{\"userFeedback\":\"NONE\",\"escalations\":[{\"@type\":\"cluster-label-change\",\"changeTime\":1609242082251,\"clusterLabel\":\"CMCD14\",\"category\":\"malicious content distribution\",\"riskCategory\":\"LOW\"},{\"@type\":\"cluster-label-change\",\"changeTime\":1608463889048,\"clusterLabel\":\"CSAL01\",\"category\":\"malware distribution\",\"riskCategory\":\"HIGH\"}],\"userNote\":null,\"confidence\":100,\"behindProxy\":false,\"flowCount\":216,\"incidentTypes\":[\"ADE\"],\"clusterLabels\":[\"CSAL01\",\"CMCD14\"],\"stateChanges\":[],\"duration\":{\"startTime\":1608453255000,\"endTime\":1609237089000},\"incidentClass\":\"malware|malware distribution\",\"userFeedbackTimestamp\":null,\"eta\":true,\"blockedFlowCount\":0,\"reoccurring\":false,\"categoriesWithRisk\":[{\"category\":\"malware distribution\",\"riskCategory\":\"HIGH\"},{\"category\":\"malicious content distribution\",\"riskCategory\":\"LOW\"}],\"osType\":\"\",\"lastUpdatedTime\":1609327978414,\"risk\":8,\"state\":{\"stateType\":\"TRIAGE\"},\"persistent\":false,\"user\":{\"userName\":\"2C:60:0C:78:A1:3C\",\"ipAddresses\":[{\"ipAddress\":\"172.24.102.142\",\"assignedFrom\":1608453255000,\"assignedTo\":1609237089000}]}},\"relationships\":{\"activities\":{\"links\":{\"self\":\"http://nginx/api/findings/v1/incidents/859a60b000b9beeb3323e58beab23de2091277ca0b661f36445db3a8e0ddd7a9/relationships/activities\",\"related\":\"http://nginx/api/findings/v1/incidents/859a60b000b9beeb3323e58beab23de2091277ca0b661f36445db3a8e0ddd7a9/activities\"}},\"clusters\":{\"links\":{\"self\":\"http://nginx/api/findings/v1/incidents/859a60b000b9beeb3323e58beab23de2091277ca0b661f36445db3a8e0ddd7a9/relationships/clusters\",\"related\":\"http://nginx/api/findings/v1/incidents/859a60b000b9beeb3323e58beab23de2091277ca0b661f36445db3a8e0ddd7a9/clusters\"}}},\"links\":{\"self\":\"http://nginx/api/findings/v1/incidents/859a60b000b9beeb3323e58beab23de2091277ca0b661f36445db3a8e0ddd7a9\"}}"
    }
],
"links": {}
}

我的代码是

import requests
import json

try:
    requests.packages.urllib3.disable_warnings()
except:
    pass

# Enter all authentication info
SMC_USER = "xxxxxxxx"
SMC_PASSWORD = "xxxxxxxx"
SMC_HOST = "xxxxxxxx"
MALICIOUS_IP = "xxxxxxxx"

# Set the URL for SMC login
url = "https://" + SMC_HOST + "/token/v2/authenticate"

# Let's create the login request data
login_request_data = {
    "username": SMC_USER,
    "password": SMC_PASSWORD
}

# Initialize the Requests session
api_session = requests.Session()

# Perform the POST request to login
response = api_session.request("POST", url, verify=False, data=login_request_data)

# If the login was successful
if (response.status_code == 200):
    url = 'https://' + SMC_HOST + '/sw-reporting/v2/tenants/0/incidents'
    response = api_session.request("GET", url, verify=False)
    # If successfully able to get list of Cognitive Intelligence incidents
    if (response.status_code == 200):
        # Loop through the list and print Cognitive Intelligence incident
        incidents = json.loads(response.content)["data"]#["incidentDetails"]
        lent = len(incidents)
        print("\t\t\t\\n", lent)
        for i in range(0, lent):

            a = incidents[i]
            b = a["ip"]
            c = a["risk"]
            d = a["incidentClassPrimary"]
            z = json.loads(response.content)
            zz = z.get("data")[0].get("incidentDetails").get("attributes").get("user").get("ipAddresses")  
    else:
        print(
            "An error has ocurred, while fetching Cognitive Intelligence incidents, with the following code {}".format(
                response.status_code))

    uri = 'https://' + SMC_HOST + '/token'
    response = api_session.delete(uri, timeout=30, verify=False)

# If the login was unsuccessful
else:
    print("An error has ocurred, while logging in, with the following code {}".format(response.status_code))

我需要得到以下值:

  1. incidentClassPrimary
  2. ip
  3. 风险
  4. 事件状态
  5. 事件详情
  6. 事件类

关于 (incidentClass) 在 (incidentDetails )

提前致谢。

【问题讨论】:

  • 这甚至不是有效的 json - 所以......祝你好运。 getting-values-from-json-using-python
  • 您为什么不止一次使用json.loads(response.content)?其次,你知道 response.json() 存在吗?

标签: python json


【解决方案1】:

看来你至少需要

details = json.loads(a["incidentDetails"])
attrs = details["attributes"] 

然后你必须解析这个以获得更多数据

如果您只需要第一个事件数据,则在您已经捕获响应后将其移出循环

【讨论】:

  • 是的@OneCricketeer 我搜索并最终得到以下答案:zz = json.loads(z) ipadd = zz["attributes"]["user"]["ipAddresses"][0]['ipAddress'] print(ipadd) category = zz["attributes"]['escalations']#['category'] category1 = zz["attributes"]["categoriesWithRisk"]#['category'] if not category1: print("empty") else: catt = category1[0]["category"] catt1 = category1[0]["riskCategory"] print(catt) print(catt1)
猜你喜欢
  • 1970-01-01
  • 2018-05-17
  • 2015-12-30
  • 1970-01-01
  • 2022-01-23
  • 2023-03-21
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
相关资源
最近更新 更多