簡體   English   中英

JSONDecodeError:期望值:Jupyter Notebook 中的第 1 行第 1 列(字符 0)

[英]JSONDecodeError: Expecting value: line 1 column 1 (char 0) in Jupyter Notebook

我正在關注這個使用 Python 的視頻,並且我在第一個項目中使用 Jupyter Notebook 來構建一個等權重的標准普爾 500 指數基金。 在 56:30 左右,我們開始將所有股票的數據提取到 Pandas DataFrame object 中。

附加所有信息的循環返回 JSONDecodeError:預期值:第 1 行第 1 列(字符 0)。 我也可能想要一種沒有 append 的替代方法來編寫此代碼,因為它將來會被棄用。 如果有幫助的話,我們正在使用來自 IEX Cloud 的沙箱 API。

該代碼在將 [:5] 放在“Ticker”之后並返回前 5 個股票信息時起作用,所以我不明白為什么包括所有股票會給出不同的響應。

代碼:

stocks = pd.read_csv('sp_500_stocks.csv')
from secrets import IEX_CLOUD_API_TOKEN

my_columns = ['Ticker', 'Stock Price', 'Market Capitalization', 'Number of Shares to Buy']

final_dataframe = pd.DataFrame(columns = my_columns)
for symbol in stocks['Ticker']:
    api_url = f'https://sandbox.iexapis.com/stable/stock/{stock}/quote/?token={IEX_CLOUD_API_TOKEN}'
    data = requests.get(api_url).json()
    final_dataframe = final_dataframe.append(
        pd.Series(
        [
            symbol,
            data['latestPrice'],
            data['marketCap'],
            'N/A'
        ],
            index = my_columns
        ),
        ignore_index = True
    )

錯誤:

    JSONDecodeError                           Traceback (most recent call last)
Input In [73], in <cell line: 2>()
      2 for stock in stocks['Ticker']:
      3     api_url = f'https://sandbox.iexapis.com/stable/stock/{stock}/quote/?token={IEX_CLOUD_API_TOKEN}'
----> 4     data = requests.get(api_url).json()
      5     final_dataframe = final_dataframe.append(
      6         pd.Series(
      7         [
   (...)
     15         ignore_index = True
     16     )

File ~\anaconda3\lib\site-packages\requests\models.py:899, in Response.json(self, **kwargs)
    897 if encoding is not None:
    898     try:
--> 899         return complexjson.loads(
    900             self.content.decode(encoding), **kwargs
    901         )
    902     except UnicodeDecodeError:
    903         # Wrong UTF codec detected; usually because it's not UTF-8
    904         # but some other 8-bit codec.  This is an RFC violation,
    905         # and the server didn't bother to tell us what codec *was*
    906         # used.
    907         pass

File ~\anaconda3\lib\json\__init__.py:346, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    341     s = s.decode(detect_encoding(s), 'surrogatepass')
    343 if (cls is None and object_hook is None and
    344         parse_int is None and parse_float is None and
    345         parse_constant is None and object_pairs_hook is None and not kw):
--> 346     return _default_decoder.decode(s)
    347 if cls is None:
    348     cls = JSONDecoder

File ~\anaconda3\lib\json\decoder.py:337, in JSONDecoder.decode(self, s, _w)
    332 def decode(self, s, _w=WHITESPACE.match):
    333     """Return the Python representation of ``s`` (a ``str`` instance
    334     containing a JSON document).
    335 
    336     """
--> 337     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338     end = _w(s, end).end()
    339     if end != len(s):

File ~\anaconda3\lib\json\decoder.py:355, in JSONDecoder.raw_decode(self, s, idx)
    353     obj, end = self.scan_once(s, idx)
    354 except StopIteration as err:
--> 355     raise JSONDecodeError("Expecting value", s, err.value) from None
    356 return obj, end

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

您可以通過檢查請求的數據是否存在來獲得相同的結果。

final_dataframe = pd.DataFrame(columns = my_columns)
lst = []
for stock in stocks['Ticker']:
    api_url = f'https://sandbox.iexapis.com/stable/stock/{stock}/quote/?token={IEX_CLOUD_API_TOKEN}'
    api_url = api_url.rstrip('\n')
    r = requests.get(api_url)
    if r:
        data = r.json()
        lst.append([stock, data['latestPrice'], data['marketCap'], 'N/A'])
final_dataframe = pd.DataFrame(lst, columns=my_columns)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM