首页 > 解决方案 > Python - 尝试以某种方式从 API 结果打印 json 数据

问题描述

现在我有:

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

这给了我以下结果:

<Response [200]>
{'matches': [{'threatType': 'MALWARE', 'platformType': 'ANY_PLATFORM', 'threat': {'url': 'http://malware.testing.google.test/testing/malware/'}, 'cacheDuration': '300s', 'threatEntryType': 'URL'}]}

我想更好地打印它/删除一些数据,所以它看起来像:

Url: 'http://malware.testing.google.test/testing/malware/'
ThreatType: 'MALWARE'
PlatformType: 'ANY_PLATFORM'

但是每次我尝试某些东西时,我都会不断收到位置参数错误

编辑:提交超过 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'}]}

标签: pythonjsonapipostparameters

解决方案


防御方法:

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

推荐阅读