0

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).

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Beautiful, thank you! Is there a way that I can change the key names, such as 'abuseConfidenceScore' to 'Abuse Confidence Score'?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.