【问题标题】:Can't format API json output correctly无法正确格式化 API json 输出
【发布时间】:2020-10-12 16:42:09
【问题描述】:

输入:

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

输出:

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

无法获取我想要的信息并将其打印在每一行,例如:

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

我尝试了类似...

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

但是 get 出错,它是一个字符串

【问题讨论】:

    标签: python json api for-loop python-requests-html


    【解决方案1】:

    respons.json() 方法返回一个字典。您可以遍历此字典的键和值并打印。

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

    如果您想打印特定键的值并在找不到该键时显示消息,您可以使用下面的代码。此代码遍历感兴趣的键,如果此键不在响应字典中,您可以打印一条消息。否则,您打印键和值。

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

    【讨论】:

    • 非常感谢!由于某种原因,这比我在构建工具的第一个 api 上的输出更像是一项任务,哈哈
    猜你喜欢
    • 2021-11-16
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-27
    相关资源
    最近更新 更多