python - 跳过循环中的错误-JSONDecodeError : Expecting value: line 1 column 1 (char 0)

标签 python json api loops error-handling

我正在运行API请求循环(每分钟30个请求)。数据以JSON格式返回,我将其转换为 Pandas 数据库(我识别列并将它们连接起来)。
有时,我的请求之一出现以下错误,该错误(自动)停止了脚本的执行。

有没有办法告诉Python跳过该错误并继续循环?

我不介意不接收和处理来自这个错误请求的数据。

如果不是那么简单,是否至少有一种方法可以获取音频通知(哔声),以便我知道并可以再次手动执行脚本?

Traceback (most recent call last):
  File "Skript.py", line 19, in <module>
    dfraw = pd.concat([pd.DataFrame({k: v}) for k, v in dataAPI.json().items() if k in columns], axis=1)
  File "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\requests\models
.py", line 898, in json

  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.752.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.752.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.752.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

这是代码:
import pandas as pd
from pathlib import Path
import time
import datetime
import requests

while True:
    start = time.process_time()
    starttime = time.time()
    list_of_underlyings = ['X','Y','Z',...]

    for i in list_of_underlyings:
        url = ("https:xyzxyz?symbol=" + i + "&resolution=1&count=50&format=json")
        dataAPI = requests.get(url)
        columns = {'c', 'h', 'l', 'o', 't' , 'v'}
        dfraw = pd.concat([pd.DataFrame({k: v}) for k, v in dataAPI.json().items() if k in columns], axis=1)
        df = dfraw.reindex(columns = ['o', 'h', 'l', 'c', 'v' , 't'])

    time.sleep(60.0 - ((time.time() - starttime) % 60.0))

最佳答案

您想要一个tryexcept块,它将尝试您的代码,如果中断,它将继续循环的下一个迭代

try:
    //your code
except:
    continue

另外,如果您希望它不执行任何操作而不是跳过该迭代,则可以使用pass代替continue

编辑:如果您尝试执行列表理解,则不可能使用try/except块,您需要执行常规的for循环以添加元素

编辑2:给定代码,您将try try块放在for循环内
import pandas as pd
from pathlib import Path
import time
import datetime
import requests

while True:
    start = time.process_time()
    starttime = time.time()
    try:

        list_of_underlyings = ['X','Y','Z',...]

        for i in list_of_underlyings:
            url = ("https:xyzxyz?symbol=" + i + "&resolution=1&count=50&format=json")
            dataAPI = requests.get(url)
            columns = {'c', 'h', 'l', 'o', 't' , 'v'}
            dfraw = pd.concat([pd.DataFrame({k: v}) for k, v in dataAPI.json().items() if k in columns], axis=1)
            df = dfraw.reindex(columns = ['o', 'h', 'l', 'c', 'v' , 't'])
    except JSONDecodeError:
        continue
    finally:
        time.sleep(60.0 - ((time.time() - starttime) % 60.0))

因此,您将尝试使用代码,如果遇到格式不正确的问题,它将捕获该问题,然后最终在给定的时间内休眠,无论您遇到了什么障碍。

关于python - 跳过循环中的错误-JSONDecodeError : Expecting value: line 1 column 1 (char 0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61352405/

相关文章:

c++ - 使用 Boost 的 JSON 数据

java - 是否可以查看 API 类的源代码?

python - numpy 数组末尾的索引

python - 如果我使用 timeit 计时函数需要多长时间,如何将函数的结果存储在变量中?

python - 如何将 Pandas 数据框中的多列弹出到新的数据框中?

java - gson 查找缺失的原始字段

python - 在使用 OOP 尝试钻石形状问题时,Python 中发生了什么

Go 语言中 JSON 嵌套结构体

java - 如何在不下载附件文件的情况下获取电子邮件正文

python - 如何将经过身份验证的用户设置为序列化器?