標準ライブラリ

json.dumps()

Pythonの辞書やリストを、JSON形式の文字列に変換します。APIへのデータ送信などでよく使われます。

構文

import json json.dumps(データ)

使用例

import json
data = {'name': '田中', 'age': 25}
print(json.dumps(data, ensure_ascii=False))

実行結果

{"name": "田中", "age": 25}

💡 実践的な使用例

import json
data = {'name': '田中', 'hobbies': ['読書', 'プログラミング']}
print(json.dumps(data, ensure_ascii=False, indent=2))

indent引数を指定すると、JSON文字列を人が読みやすいインデント付きの形(整形出力)にできます。設定ファイルの保存やログ出力によく使われます。

関連トピック

AI JSON json.JSONDecodeError

← メソッド辞典に戻る