【问题标题】:JSONDecodeError when using for loop in python [duplicate]在python中使用for循环时出现JSONDecodeError [重复]
【发布时间】:2021-05-29 15:55:50
【问题描述】:

我一直在尝试执行一些 API 查询来获取我的 DF 中的一些缺失数据。我正在使用 grequest 库发送多个请求并为响应对象创建一个列表。然后我使用 for 循环将响应加载到 json 中以检索丢失的数据。我注意到的是,当使用 .json() 从列表中直接使用 notition list[0].json() 加载数据时,它工作正常,但是当尝试读取列表然后将响应加载到 json 中时,此错误出现:JSONDecodeError: Expecting value: line 1 column 1 (char 0)

这是我的代码:

import requests 
import json
import grequests

ls = []
for i in null_data['name']:
    url = 'https://pokeapi.co/api/v2/pokemon/' + i.lower()
    ls.append(url)
rs  = (grequests.get(u) for u in ls)
s = grequests.map(rs)
#This line works
print(s[0].json()['weight']/10)

for x in s:
    #This one fails
    js = x.json()
    peso = js['weight']/10
    null_data.loc[null_data['name'] == i.capitalize(), 'weight_kg'] = peso
<ipython-input-21-9f404bc56f66> in <module>
     13 
     14 for x in s:
---> 15     js = x.json()
     16     peso = js['weight']/10
     17     null_data.loc[null_data['name'] == i.capitalize(), 'weight_kg'] = peso

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

【问题讨论】:

    标签: python json api loops for-loop


    【解决方案1】:

    一个(或多个)元素为空。

    所以:

    ...
    for x in s:
        if x != ""
            js = x.json()
            peso = js['weight']/10
            null_data.loc[null_data['name'] == i.capitalize(), 'weight_kg'] = peso
    ...
    

    ...
    for x in s:
        try:
            js = x.json()
            peso = js['weight']/10
            null_data.loc[null_data['name'] == i.capitalize(), 'weight_kg'] = peso
        except json.JSONDecodeError as ex: print("Failed to decode(%s)"%ex)
    ...
    

    第一个检查 x 是否为空字符串,而另一个尝试解码每个字符串,但出现异常时仅打印错误消息而不是退出。

    【讨论】:

      猜你喜欢
      • 2020-10-18
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 2016-12-31
      • 2019-09-19
      • 1970-01-01
      • 2016-09-04
      • 2018-06-20
      相关资源
      最近更新 更多