首页 > 解决方案 > Python - 解析 JSON 结果

问题描述

如何解析以下 JSON 结果以打印出我需要的内容?

{“数据”:{“abuseConfidenceScore”:100,“国家代码”:“ZW”,“域”:“dandemutande.co.zw”,“主机名”:[“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",

我想打印出“abuseConfidenceScore”“isWhitelisted”对象。

输出应该是这样的:

滥用信心评分 100

isWhitelisted false

本质上,我想在对象(数据)中打印一个对象(abuseConfidenceScore),而不是整个对象(数据)。

标签: jsonpython-3.x

解决方案


解决这类问题的一个好方法是首先检查 json 的深度,我的意思是深度,嵌套了多少字典,所以在加载 dict 之后,

{'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'}}

在这里,depth = 2 dicts 因此,我们将进行双循环并检查您需要的键

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]}')

希望它对你有帮助:D

好吧,只有当它们是骆驼式的时候,你才能在字符串中分离这些词,就像这个一样

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

推荐阅读