【问题标题】:Error when get json from Requests.get()从 Requests.get() 获取 json 时出错
【发布时间】:2017-05-14 20:23:07
【问题描述】:

我使用 requests.get 从我的网页获取 json,但在运行我的代码时收到了一些错误。 这是我的代码:

def get(t):
while 1:
    r = requests.get('http://raspberry.site11.com/controller.php')
    while r.status_code != 200:
        r = requests.get('http://raspberry.site11.com/controller.php')      
    d=r.json()
    dv1=d["Dv1"]
    dv2=d["Dv2"]
    dv3=d["Dv3"]
    dv4=d["Dv4"]    

    if dv1=="1":
        GPIO.output(6,0)
    else:
        GPIO.output(6,1)        
    if dv2=="1":
        GPIO.output(13,0)
    else:
        GPIO.output(13,1)           
    if dv3=="1":
        GPIO.output(19,0)
    else:
        GPIO.output(19,1)       
    if dv4=="1":
        GPIO.output(26,0)
    else:
        GPIO.output(26,1)   
    time.sleep(t)

这是我收到的错误:

    Unhandled exception in thread started by <function get at 0xb6506930>
Traceback (most recent call last):
  File "thread.py", line 33, in get
    d=r.json()
  File "/usr/lib/python2.7/dist-packages/requests/models.py", line 793, in json
    return json.loads(self.text, **kwargs)
  File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 369, in decode
    raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 4 - line 1 column 10 (char 3 - 9)

希望大家帮助我,非常感谢。

【问题讨论】:

  • 您的端点未返回 JSON。但是,如果看不到它做了什么返回,我们就无能为力了。
  • 似乎对我有用?也许这与您在 while 循环中调用它并最终使服务器超载的事实有关?也许您应该捕获错误并记录r.content。当您发现错误时,请尝试检查您的服务器日志。最后一条评论,您的网页使用了错误的内容类型:text/html。应该是application/json
  • 非常感谢。我的问题是由互联网连接质量造成的,所以我换了另一台主机。 ^^

标签: python json get request


【解决方案1】:

我觉得你可以的

def get_json(data):
    try:
        return data.json()
    except ValueError:
        return False

然后

def get(t):
    while 1:
        r = requests.get('http://raspberry.site11.com/controller.php')
        while not get_json(r):
            r = requests.get('http://raspberry.site11.com/controller.php')      
        d = get_json(r)

【讨论】:

  • 非常感谢。我的问题是由互联网连接质量造成的,所以我换了另一台主机。 ^^
猜你喜欢
  • 1970-01-01
  • 2017-01-15
  • 1970-01-01
  • 1970-01-01
  • 2018-12-27
  • 1970-01-01
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多