[英]Python - Trying to print json data from API results in a certain way
Right now I have:现在我有:
import json
api_key = '123456'
url = "https://safebrowsing.googleapis.com/v4/threatMatches:find"
payload = {'client': {'clientId': "mycompany", 'clientVersion': "0.1"},
'threatInfo': {'threatTypes': ["SOCIAL_ENGINEERING", "MALWARE"],
'platformTypes': ["ANY_PLATFORM"],
'threatEntryTypes': ["URL"],
'threatEntries': [{'url': "http://malware.testing.google.test/testing/malware/"}]}}
params = {'key': api_key}
r = requests.post(url, params=params, json=payload)
# Print response
print(r)
print(r.json())
Which gives me the results of:这给了我以下结果:
<Response [200]>
{'matches': [{'threatType': 'MALWARE', 'platformType': 'ANY_PLATFORM', 'threat': {'url': 'http://malware.testing.google.test/testing/malware/'}, 'cacheDuration': '300s', 'threatEntryType': 'URL'}]}
I want to print it more nicely / drop some data so it looks like:我想更好地打印它/删除一些数据,使其看起来像:
Url: 'http://malware.testing.google.test/testing/malware/'
ThreatType: 'MALWARE'
PlatformType: 'ANY_PLATFORM'
But every time I try something I just keep getting positional argument errors但是每次我尝试一些东西时,我都会不断收到位置参数错误
Edit: Having more than 2 urls submitted gives the following output编辑:提交超过 2 个 url 会提供以下输出
{'matches': [{'threatType': 'MALWARE', 'platformType': 'ANY_PLATFORM', 'threat': {'url': 'http://malware.testing.google.test/testing/malware/'}, 'cacheDuration': '300s', 'threatEntryType': 'URL'}, {'threatType': 'MALWARE', 'platformType': 'ANY_PLATFORM', 'threat': {'url': 'http://malware.testing.google.test/testing/malware/'}, 'cacheDuration': '300s', 'threatEntryType': 'URL'}]}
A defensive approach:防御方法:
for match in r.json().get('matches', []):
print(f'URL: {match.get("threat", {}).get("url", "Unknown URL")}')
print(f'threatType: {match.get("threatType", "Unknown ThreadType")}')
print(f'platformType: {match.get("platformType", "Unknown PlatformType")}')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.