json - 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),而不是整个对象(数据)。
解决方案
解决这类问题的一个好方法是首先检查 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))
推荐阅读
- python-sphinx - 如何展开和折叠目录
- scala - Akka 类变量范围问题
- python - AssertionError(AssertionError:视图函数映射正在覆盖现有端点函数:conpab 127.0.0.1)
- reactjs - 在不使用模型的情况下将 React 的数据存储在 Django 数据库中
- kotlin - Uma matriz A de N inteiros, retorna o menor inteiro positivo (maior que 0) que não ocorre em A
- python - django 如何在发布前查看博客评论?
- django - Gunicorn tmp 文件夹获取我的空文件
- python - to_csv,错误:需要转义,但没有设置转义字符和 copy_from StringDataRightTruncation: value too long for type character
- llvm-ir - 如何让 llc 优化 ll 文件?
- c++ - 结构不保存成员变量值