Python学習チャンネル by PyQ

Pythonのオンライン学習プラットフォームPyQのオフィシャルブログです

【Pythonお悩み解決】TypeError: the JSON object must be str, bytes or bytearray とは何ですか?

こんにちは、PyQサポートです。
今回は TypeError: the JSON object must be str, bytes or bytearray というエラーの意味と、その原因を解説します。

質問:TypeError: the JSON object must be str, bytes or bytearray の原因は?

TypeError: the JSON object must be str, bytes or bytearray, not int というエラーが出ました。このエラーの原因を教えてください。

入力した内容(コード)

import json

json.loads(100)

出たエラー(実行結果)

Python 3.10 で実行した結果

Traceback (most recent call last):
  File "//sample.py", line 3, in <module>
    json.loads(100)
  File "/usr/local/lib/python3.10/json/__init__.py", line 339, in loads
    raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not int

回答:JSONとして扱えないオブジェクトを入力したためです。

今回のエラーの原因は、JSONとして扱えないオブジェクトを入力したためです。
json.loads は、JSON文字列をPythonのオブジェクトに変換するための関数であるため、引数に入力する値は文字列型・バイト型・バイト配列型のオブジェクトである必要があります。

import json

print(json.loads('100'))
print(json.loads(b'100'))
print(json.loads(bytearray(b'100')))

実行結果

100
100
100

このように、文字列型・バイト型・バイト配列型の値ではエラーが発生せず、正しい結果を表示できます。

それ以外の整数型の 100 や、論理型の True 、 辞書型の {'value': 100} などといった型のオブジェクトを入力すると、今回のようなエラーが表示されます。

今回のようなエラーが出た時は、一度 json.loads 関数の引数に正しく文字列が渡されているかを確認してみましょう。

補足:jsonモジュールについて

JSON文字列をPythonオブジェクトに変換するには

今回のように、 json.loads 関数を使います。

import json

j = '{"value": 100}'
v = json.loads(j)
print(v)
print(v["value"])

実行結果

{'value': 100}
100

json.loads 関数の引数には、JSONとして解釈できる文字列を入力する必要があります。

PythonオブジェクトをJSON文字列に変換するには

json.dumps 関数を使います。

import json

v = {"value": 100}
j = json.dumps(v)
print(j)

実行結果

'{"value": 100}'

json.loads 関数の引数には、JSONで使用できる型を入力する必要があります。
例えば、Pythonには日付を表すdatetime型がありますが、JSONでは使用できない型のためエラーになります。

その他のTypeError

TypeError: unsupported operand type(s) for /: 'str' and 'int'

blog.pyq.jp

TypeError: can only concatenate list (not "tuple") to list

blog.pyq.jp

TypeError: can only concatenate str (not "int") to str

blog.pyq.jp

Copyright ©2017- BeProud Inc. All rights reserved.