ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Python] JSONDecodeError Traceback (most recent call last)
    Data Analysis/Python 2026. 2. 27. 23:14

    Table of Contents

    1. Introduction
    2. StockListing Error
    3. 조치 방법
    4. Reference

     

    Introduction

     AI의 생활화로 반려 LLM에 의한 파이썬이 일상에 자연스럽게 녹고 있으며, 비개발자가 코딩하는게 자연스러운 상황이다. 디버깅 조차도 Chat-GPT나 Gemini, 클로드로 충분히 할 수 있을 정도로 늘어났으나 자연어로 디버깅에 한계는 아직도 존재하는 것으로 나타난다. LLM의 최신 버전이 나올때마다 특이점이 점점 다가오는 것을 느낌에도 불구하고 언어에 대한 이해도를 높히기 위해 왜 에러가 발생하는지 파악한다면 큰 도움이 될 것이다.

    StockListing 경고 메시지 원인

    StockListing 함수는 FinanceDataReader 라이브러리에 담긴 함수이다. 해당 함수는 특정 시장별 주식 목록을 불러오는 함수로 "KOSPI"를 입력할 경우 KOSPI에 포함된 940 종목을 불러오게 된다. 이때, 함수는 거래소 서버에 데이터를 요청했는데, 서버가 정상적인 데이터(JSON) 대신 **빈 값이나 에러 페이지(HTML)**를 보냈기 때문에 발생한다.

    import FinanceDataReader as fdr
    
    fdr.StockListing('KOSPI')
    
    ---------------------------------------------------------------------------
    JSONDecodeError                           Traceback (most recent call last)
    Cell In[11], line 1
    ----> 1 fdr.StockListing('KOSPI')
    
    File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\FinanceDataReader\data.py:160, in StockListing(market, start, end)
        158 market = market.upper()
        159 if market in ['KRX', 'KOSPI', 'KOSDAQ', 'KONEX', 'KRX-MARCAP']:
    --> 160     return KrxMarcapListing(market).read()
        161 elif market in ['KRX-DESC', 'KOSPI-DESC', 'KOSDAQ-DESC', 'KONEX-DESC']:
        162     return KrxStockListing(market).read()
    
    File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\FinanceDataReader\krx\listing.py:43, in KrxMarcapListing.read(self)
         34 data = {
         35     'bld': 'dbms/MDC/STAT/standard/MDCSTAT01501',
         36     'mktId': mkt_map[self.market], # 'ALL'=전체, 'STK'=KOSPI, 'KSQ'=KOSDAQ, 'KNX'=KONEX
       (...)
         40     'csvxls_isNo': 'false',
         41 }
         42 html_text = requests.post(url, headers=self.headers, data=data).text
    ---> 43 j = json.loads(html_text)
         44 df = pd.DataFrame(j['OutBlock_1'])
         45 df = df.replace(r',', '', regex=True)
    
    File ~\AppData\Local\Programs\Python\Python312\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 ~\AppData\Local\Programs\Python\Python312\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 ~\AppData\Local\Programs\Python\Python312\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)

     

    조치 방법

     StockListing('KOSPI') 함수는 FinanceDataReader 라이브러리로 묶여있기 때문에 원래 작성한 라이브러리 개발자가 수정하기 전까지는 개선을 할 수 없기 때문에 다른 라이브러리를 사용하는 것이 해결 방법이다. 가장 간편한 방법으로 pykrx를 사용한다. 비교적 KRX 서버 통신이 안정적이기 때문에 대안이 될 수 있으나 이 부분도 경우에 따라 FinanceDataReader와 마찬가지로 함수 사용에 제한이 발생할 수 있다.

    from pykrx import stock

     

    Reference

    FinanceDataReader, FinanceData, "https://github.com/FinanceData/FinanceDataReader"

    댓글

Designed by Tistory.