【问题标题】:Subsetting the output data from an API request对 API 请求的输出数据进行子集化
【发布时间】:2021-12-13 23:47:00
【问题描述】:

我正在使用以下代码从 API 获取一些数据:

import requests

url = "http://prognos.konj.se/PxWeb/api/v1/sv/SenastePrognosen/f06_rantorochvaxelkurser/F0604.px"

querystring = {
  "query": [
    {
      "code": "variabel",
      "selection": {
        "filter": "item",
        "values": [
          "F0604Repo_u"
        ]
      }
    },
    {
      "code": "period",
      "selection": {
        "filter": "item",
        "values": [
          "321",
          "322",
          "323",
          "324"
        ]
      }
    }
  ],
  "response": {
    "format": "px"
  }
}

response = requests.post(url, json=querystring)

print(response.text)

打印语句产生以下答案(为简洁起见,省略所有输出):

LINK[en]="http://www.konj.se/prognosdokumentationpx";
DATA=
-0.2500 -0.2500 -0.2500 0.0000 
;

现在我只想获取 DATA 部分。我的第一个想法是: 打印(响应[“数据”])

产生错误:

TypeError: 'Response' object is not subscriptable

关于如何做到这一点的任何建议,即获取输出的数据部分?

编辑: 遵循@joshmerandas 的回答会产生错误:

json = response.json()
Traceback (most recent call last):

  File "<ipython-input-68-45bbb244f888>", line 1, in <module>
    json = response.json()

  File "C:MyUserProfile\anaconda3\lib\site-packages\requests\models.py", line 898, in json
    return complexjson.loads(self.text, **kwargs)

  File "C:\Users\C:MyUserProfile\anaconda3\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)

  File "C:\Users\C:MyUserProfile\anaconda3\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())

  File "C:\Users\C:MyUserProfile\anaconda3\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None

JSONDecodeError: Expecting value

【问题讨论】:

    标签: python typeerror


    【解决方案1】:

    你需要先访问response中的json数据,然后再从returne json中拉取数据。请参阅Response 对象的文档。你会找到json(**kwargs) 方法。所以你从 json 访问 "Data" 字段,你会遇到类似的事情:

    response = requests.post(url, json=querystring)
    json = response.json()
    
    data = json["Data"]
    
    print(data)
    

    【讨论】:

    • 使用.json() 会引发json.decoder.JSONDecodeError
    • 查看编辑@joshmeranda。不知道为什么会这样?
    • 这将是由响应中的无效/格式错误的 json 数据引起的。 Response.json 本质上只是 josn.loads 的一个包装器,它会引发错误“如果要反序列化的数据不是有效的 JSON 文档,则会引发 JSONDecodeError。”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 2017-11-21
    • 2013-08-15
    • 2022-01-08
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多