JSON(JavaScript Object Notation)は、ウェブAPIや設定ファイルなどで広く使われる、軽量なデータ交換フォーマットです。Pythonの標準ライブラリであるjson
モジュールは、Pythonのデータ構造(辞書やリスト)とJSON形式の文字列を相互に変換するためのシンプルな機能を提供します。
JSONとPythonのデータ型の対応
json
モジュールは、Pythonのデータ型とJSONのデータ型を以下のように対応させて変換します。
JSON | Python |
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
json.loads()
:JSON文字列をPythonオブジェクトに変換
json.loads()
関数(load stringの意)は、JSON形式の文字列を引数として受け取り、対応するPythonオブジェクト(通常は辞書またはリスト)に変換します。このプロセスはデシリアライズ
と呼ばれます。
import json
# JSON形式の文字列
json_string = '{"user": "Taro", "id": 101, "isActive": true, "groups": ["admin", "editor"]}'
# JSON文字列をPythonの辞書に変換
user_data = json.loads(json_string)
print(user_data)
print(f"ユーザー名: {user_data['user']}")
print(f"所属グループ: {user_data['groups']}")
実行結果:
{'user': 'Taro', 'id': 101, 'isActive': True, 'groups': ['admin', 'editor']}
ユーザー名: Taro
所属グループ: ['admin', 'editor']
JSONのtrue
がPythonのTrue
に変換されていることがわかります。
json.dumps()
:PythonオブジェクトをJSON文字列に変換
json.dumps()
関数(dump stringの意)は、Pythonのオブジェクト(辞書やリスト)を引数として受け取り、JSON形式の文字列に変換します。このプロセスはシリアライズ
と呼ばれます。
import json
# Pythonの辞書オブジェクト
python_dict = {
'productName': 'Laptop',
'price': 120000,
'inStock': True,
'specs': None
}
# Pythonの辞書をJSON文字列に変換
json_output_string = json.dumps(python_dict, indent=4, ensure_ascii=False)
print(json_output_string)
indent=4
は、出力されるJSON文字列を人間が読みやすいように4スペースでインデントするためのオプションです。ensure_ascii=False
は、日本語などの非ASCII文字が正しく表示されるようにするための指定です。
実行結果:
{
"productName": "Laptop",
"price": 120000,
"inStock": true,
"specs": null
}
補足:json.load()
とjson.dump()
loads()
とdumps()
が文字列を扱うのに対し、load()
とdump()
(sが付かない)はファイルオブジェクトを直接扱います。
json.load(file_object)
: JSONファイルを読み込み、Pythonオブジェクトに変換します。 json.dump(python_object, file_object)
: PythonオブジェクトをJSONファイルに書き込みます。
# # dump()でファイルに書き出す例
# with open('product.json', 'w', encoding='utf-8') as f:
# json.dump(python_dict, f, indent=4, ensure_ascii=False)
# # load()でファイルから読み込む例
# with open('product.json', 'r', encoding='utf-8') as f:
# loaded_data = json.load(f)
# print(loaded_data['productName'])
まとめ
json
モジュールは、Web APIとの通信や設定ファイルの管理など、現代のプログラミングで頻繁に遭遇するJSONデータを扱うための必須ツールです。json.loads()
でJSON文字列をPythonに、json.dumps()
でPythonオブジェクトをJSON文字列に変換するのが基本です。ファイルと直接やり取りする場合は、json.load()
とjson.dump()
を使用します。