簡體   English   中英

Python - 嘗試以某種方式從 API 結果打印 json 數據

[英]Python - Trying to print json data from API results in a certain way

現在我有:

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

防御方法:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM