Pythonのrequestsで「json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)」エラーが出力された場合の対応

Pythonのrequestsで「json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)」エラーが出力された場合の対応をご紹介します。

条件

  • Python 3.7.0

Pythonのrequestsでエラー

PythonのHTTP通信を行うライブラリで以下のようなエラーが発生する場合があります。

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

例えば以下のようなソースで発生します。

import requests

r = requests.get('https://www.yahoo.co.jp/')
result = r.json()
print(result)

原因

レスポンスの「Content-Type」がjson形式ではないことが原因です。
⇒json形式ではないため、json()の処理でエラーが発生します。

前述のエラーサンプルのヘッダー内容を確認すると以下のようになりました。
(’content-type’: ‘text/html; となっていることがわかります。)

import requests

r = requests.get('https://www.yahoo.co.jp/')
print(r.headers)
{'date': 'Wed, 30 Oct 2019 06:51:28 GMT', 'p3p': 'policyref="http://privacy.yahoo.co.jp/w3c/p3p_jp.xml", CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV"', 'x-content-type-options': 'nosniff', 'x-xss-protection': '1; mode=block', 'x-frame-options': 'SAMEORIGIN', 'vary': 'Accept-Encoding', 'content-encoding': 'gzip', 'expires': '-1', 'pragma': 'no-cache', 'cache-control': 'private, no-cache, no-store, must-revalidate', 'content-length': '4921', 'content-type': 'text/html; charset=UTF-8', 'Age': '0', 'Connection': 'keep-alive', 'Via': 'http/1.1 edge2443.img.djm.yahoo.co.jp (ApacheTrafficServer [c sSf ])', 'Server': 'ATS'}

対応

レスポンスのヘッダー情報を確認したうえで、json()を行うようにします。

import requests

url = 'https://github.com/timeline.json' # 'Content-Type': 'application/json;
# url = 'https://www.yahoo.co.jp/'

r = requests.get(url)

if 'json' in r.headers.get('content-type'):
    result = r.json()
    print(result)
else:
    result = r.text
    print(result)

実行結果

‘Content-Type’: ‘application/json; の場合

{'message': 'Hello there, wayfaring stranger. If you’re reading this then you probably didn’t see our blog post a couple of years back announcing that this API would go away: http://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.', 'documentation_url': 'https://developer.github.com/v3/activity/events/#list-public-events'}

‘Content-Type’: ‘application/json; ではない場合

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="content-style-type" content="text/css">
<meta http-equiv="content-script-type" content="text/javascript">
<meta name="description" content="日本最大級のポータルサイト。検索、オークション、ニュース、メール、コミュニティ、ショッピング、など80以上のサービスを展開。あなたの生活をより豊かにする「ライフ・エンジン」を目指していきます。">
<meta name="robots" content="noodp">
<meta name="google-site-verification" content="fsLMOiigp5fIpCDMEVodQnQC7jIY1K3UXW5QkQcBmVs">
<link rel="canonical" href="https://www.yahoo.co.jp/" />
<link rel="alternate" media="only screen and (max-width: 640px)" href="https://m.yahoo.co.jp/">
<link rel="alternate" href="android-app://jp.co.yahoo.android.yjtop/yahoojapan/home/top">
<title>Yahoo! JAPAN</title>
・・・

参考

GitHub:requests

https://github.com/psf/requests/issues/4908

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です