如何解决JSONDecodeError?

时间:2019-04-15 08:13:01

标签: python json python-requests

我正在使用requests Python库,以应用request.post()并将某些信息保存为响应对象。一切似乎都正确,但是我无法将响应转换为json()文件。

我已经尝试将内容解码为'utf-8',但似乎无法解决问题。我还尝试使用re模块在请求的响应内容中提取JSON。

# importing the requests library 
import requests 
import json

# api-endpoint 
URL='http://www.aguacanal.es/regantes/'

# defining a params dict for the parameters to be sent to the API 
PARAMS = {"idsector":"5","arqueta":"961","tipocontador":"21","fechaini":"04/04/2019","fechafin":"04/04/2019 23:00",}

# sending get request and saving the response as response object 
r = requests.post(url = URL, params = PARAMS,stream=True) 

print(r.status_code)  

r.json()
Traceback (most recent call last):

  File "<ipython-input-35-52b7ec8d97cc>", line 1, in <module>
    r.json()

  File "C:\Users\sara.iglesias\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\models.py", line 896, in json
    return complexjson.loads(self.text, **kwargs)

  File "C:\Users\sara.iglesias\AppData\Local\Continuum\anaconda3\lib\json\__init__.py", line 348, in loads
    return _default_decoder.decode(s)

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

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

JSONDecodeError: Expecting value

1 个答案:

答案 0 :(得分:1)

您的代码返回的是html而不是json。

r.content
Out[10]: b'<!DOCTYPE html>\n<!--[if IE 7]>\n<html class="ie ie7">\n<![endif]-->\n<!--[if IE 8]>\n<html class="ie ie8">\n<![endif]-->\n<!--[if !(IE 7) | !(IE 8)]-->\n<html lang="es-ES" prefix="og: http://ogp.me/ns#" xmlns:og="https://ogp.me/ns#" xmlns:fb="https://www.facebook.com/2008/fbml">\n<!--<![endif]-->\n<head>\n    <meta charset="UTF-8" />\n    <meta name="viewport" content="width=device-width" />\n ...