Harper
Harper

Reputation: 25

Python - Parse JSON results

How do I parse the below JSON results to print out what I need?

{ "data": { "abuseConfidenceScore": 100, "countryCode": "ZW", "domain": "dandemutande.co.zw", "hostnames": [ "ip-net-196-43-114-234.africaonline.co.zw" ], "ipAddress": "196.43.114.234", "ipVersion": 4, "isPublic": true, "isWhitelisted": false, "isp": "Africa Online Zimbabwe", "lastReportedAt": "2021-06-19T10:32:46+00:00",

I want to print out the "abuseConfidenceScore" and "isWhitelisted" objects.

The output should be like:

abusedConfidenceScore 100

isWhitelisted false

Essentially, I want to print an object (abuseConfidenceScore) within an object (data) rather than the whole object (data).

Upvotes: 0

Views: 54

Answers (1)

Oreo
Oreo

Reputation: 119

A good approach to these type of problems is to first check the depth of json , and by depth I mean , how many dictionaries are nested,so after loading the dict would be,

{'data': {'abuseConfidenceScore': 100, 'countryCode': 'ZW', 'domain': 'dandemutande.co.zw', 'hostnames': ['ip-net-196-43-114-234.africaonline.co.zw'], 'ipAddress': '196.43.114.234', 'ipVersion': 4, 'isPublic': True, 'isWhitelisted': False, 'isp': 'Africa Online Zimbabwe', 'lastReportedAt': '2021-06-19T10:32:46+00:00'}}

here, depth = 2 dicts thus, we are gonna make a double loop and check for your required keys

f = {'data': {'abuseConfidenceScore': 100, 'countryCode': 'ZW', 'domain': 'dandemutande.co.zw', 'hostnames': ['ip-net-196-43-114-234.africaonline.co.zw'], 'ipAddress': '196.43.114.234', 'ipVersion': 4, 'isPublic': True, 'isWhitelisted': False, 'isp': 'Africa Online Zimbabwe', 'lastReportedAt': '2021-06-19T10:32:46+00:00'}}
for first_dict_keys in f.keys():
     if first_dict_keys == 'data':
         for second_dict_key_val in f['data'].items(): #will return a tuple of key and value
              if second_dict_key_val[0] in ['abuseConfidenceScore','isWhitelisted']: #since they both are in the same dict
                 print(f'{second_dict_key_val[0]} {second_dict_key_val[1]}')

hope it helped you :D

well you can sepratae those words in the string only if they are in camel case like in this one

x = 'abuseConfidenceScore'
def camel_case_parser(s):
     res = ''
     for char in s:
          if char.islower():
               res += char
          else:
               res += f' {char}'
     return res
print(camel_case_parser(x))

Upvotes: 1

Related Questions