简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM