简体   繁体   English

无法正确格式化 API json 输出

[英]Can't format API json output correctly

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但是得到一个错误并且它是一个字符串

The respons.json() method returns a dictionary. respons.json()方法返回一个字典。 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}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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