Can't format API json output correctly

162 views Asked by At

Input:

import requests
import json
apikey2 = '1234'
headers = {'API-Key':apikey2,'Content-Type':'application/json'}
data = {"url":urlz2, "visibility": "private"}
r2 = requests.post('https://urlscan.io/api/v1/scan/',headers=headers, data=json.dumps(data))
print(r2)
print(r2.json())

Output:

<Response [200]>
{'message': 'Submission successful', 'uuid': 'xxxxxxxx', 'result': 'https://urlscan.io/result/xxxxxxxxxx/', 'api': 'https://urlscan.io/api/v1/result/xxxxxxxxxxx/', 'visibility': 'private', 'options': {'useragent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/xxxxxxxx Safari/xxxxxx'}, 'url': 'https://xxxxxxx.io/'}

Having trouble grabbing the information I want and printing it on each line like:

message: Submission successful
uuid: xxxxxxxx
result: https://urlscan.io/result/xxxxxxxxxx/
visibility: private

I tried something along the lines of...

for match in r2.json().get('message', []):
    print(f'uuid: {message.get("uuid", {}).get("uuid", "Unknown uuid")}')

but get an error with get and it being a string

1

There are 1 answers

1
jkr On BEST ANSWER

The respons.json() method returns a dictionary. You can iterate over the keys and values of this dictionary and print.

import requests
import json
apikey2 = '1234'
headers = {'API-Key':apikey2,'Content-Type':'application/json'}
data = {"url":urlz2, "visibility": "private"}
r2 = requests.post('https://urlscan.io/api/v1/scan/',headers=headers, data=json.dumps(data))
print(r2)
dictionary = r2.json()

for key, value in dictionary.items():
    print(f"{key} = {value}")

If you want to print the values of specific keys and a message if that key is not found, you can use the code below. This code iterates over the keys of interest, and if this key is not in the response dictionary, you can print a message. Otherwise, you print the key and value.

keys = ["message", "uuid", "result", "visibility"]
response_dict = r2.json()
for key in keys:
    value = response_dict.get(key, None)
    if value is None:
        print(f"{key} = Unknown {key}")
    else:
        print(f"{key} = {value}")