【问题标题】:How to parse JSON data from Digital Ocean API如何从 Digital Ocean API 解析 JSON 数据
【发布时间】:2020-12-01 14:34:26
【问题描述】:

您好,我正在尝试使用数字海洋 API 构建应用程序,所以基本上我使用请求库(Python)向https://api.digitalocean.com/v2/droplets 发送请求,这是我的代码

import requests
host = "https://api.digitalocean.com"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer MYTOKEN"
    }
dataa = {}
api = requests.post(f"{host}/v2/droplets", headers= headers, data=json.dumps(dataa))

然后尝试访问data = api.json() API 返回的信息 如果我尝试通过运行print(data['droplet']['id']) 来打印 id,我会遇到这个错误

Traceback (most recent call last):
  File "/home/gogamic/code/gogamic-website/functions.py", line 276, in <module>
    create_new_server('mai@gogamic.com', 2)
  File "/home/gogamic/code/gogamic-website/functions.py", line 260, in create_new_server
    server_info = json.loads(infoo.json())
  File "/usr/lib/python3/dist-packages/requests/models.py", line 898, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3/dist-packages/simplejson/__init__.py", line 525, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 370, in decode
    obj, end = self.raw_decode(s)
  File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 400, in raw_decode
    return self.scan_once(s, idx=_w(s, idx).end())
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

这是从 API 返回的JSON

【问题讨论】:

  • 您可以尝试打印响应正文,print(api.text),我想您会收到错误,因为响应不是 json 并且.json() 正在尝试将其转换为 json,即使这是一个无效的。
  • 它返回一个字符串,但我无法循环遍历它
  • 在没有看到实际响应的情况下很难说出了什么问题,可能是编码的?

标签: json python-3.x api python-requests digital-ocean


【解决方案1】:

该 API 方法是 GET 而不是 POST

https://developers.digitalocean.com/documentation/v2/#list-all-droplets

你的代码可以代替我:

api = requests.post(f"{host}/v2/droplets",
                    headers= headers,
                    data=json.dumps(dataa))

与:

api = requests.get(f"{host}/v2/droplets",
                    headers= headers,
                    data=json.dumps(dataa))

并根据@fixatd 添加:

print(api)

产量:

<Response [200]>

注意我没有要列出的水滴。

为了完整起见,创建一个 Droplet 并重新运行:

doctl compute droplet create stackoverflow-65092533 \
--region sfo3 \
--size s-1vcpu-2gb \
--ssh-keys ${KEY} \
--tag-names stackoverflow \
--image ubuntu-20-10-x64

然后:

使用:

content = resp.json()

if resp.status_code != 200:
    print("Unexpected status code: {}".format(resp.status_code))
    quit()

for droplet in content["droplets"]:
    print("ID: {}\tName: {}".format(droplet["id"], droplet["name"]))

产量:

ID: 219375538   Name: stackoverflow-65092533

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-09
    • 2022-08-23
    • 2020-06-14
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    相关资源
    最近更新 更多