Home > Net >  How can I assign a variable from a string inside a json dictionary?
How can I assign a variable from a string inside a json dictionary?

Time:10-08

This is my get output on each asset im getting data back from

enter image description here

I can access the dictionary values easily,

page = json_response["page"].get("number", 0)

but how doo i access the value of the array, i want to be able to add up each critical vulnerability

this is the return, im trying to get critical, moderate, severe values from the vulnerabilities sub array

{'links': [{}],
 'page': {'number': 6, 'size': 10, 'totalPages': 13, 'totalResources': 123},
 'resources': [{'addresses': [],
                'assessedForPolicies': False,
                'assessedForVulnerabilities': True,
                'configurations': [],
                'databases': [],
                'files': [],
                'history': [],
                'hostName': 'corporate-workstation-1102DC.acme.com',
                'hostNames': [],
                'id': 282,
                'ids': [],
                'ip': '182.34.74.202',
                'links': [],
                'mac': 'AB:12:CD:34:EF:56',
                'os': 'Microsoft Windows Server 2008 Enterprise Edition SP1',
                'osFingerprint': {},
                'rawRiskScore': 31214.3,
                'riskScore': 37457.16,
                'services': [],
                'software': [],
                'type': '',
                'userGroups': [],
                'users': [],
                'vulnerabilities': {'critical': 16,
                                    'exploits': 4,
                                    'malwareKits': 0,
                                    'moderate': 3,
                                    'severe': 76,
                                    'total': 95}}]}

CodePudding user response:

You've done a poor job of explaining it, but I'd bet that resources is a list of multiple dictionaries in your original data, and you want to do something with all of those values.

vulnerabilities = []
resources = json_response['resources']
for d in resources:
    if 'vulnerabilities' in d:
        vulnerabilities.append(d['vulnerabilities'])

print(vulnerabilities)
print(sum(x.get('critical', 0) for x in vulnerabilities))
print(sum(x.get('severe', 0) for x in vulnerabilities))

Output:

[{'critical': 16, 'exploits': 4, 'malwareKits': 0, 'moderate': 3, 'severe': 76, 'total': 95}]
16
76

CodePudding user response:

You can read vulnerabilities like this,

json.loads(json_response)['resources'][0]['vulnerabilities']['critical']

# Out
16

CodePudding user response:

If you want to pull the value the way you know how instead of using json try:

crit_value = json_response["resources"][0]["vulnerabilities"].get("critical", 16)
  • Related