投稿

[Python 100日チャレンジ] Day 43 - JSONデータを扱う

PythonのjsonモジュールでJSONを読み書きし、dictとJSON文字列を相互に変換する方法を学びます。

[Python 100日チャレンジ] Day 43 - JSONデータを扱う

JSONとは

JSONは、APIや設定ファイルでよく使われるデータ形式です。Pythonではdictやlistに近い形で扱えます。

1
2
3
4
5
import json

text = '{"name": "Yuna", "age": 28}'
data = json.loads(text)
print(data["name"])

JSONファイルを読む

1
2
with open("user.json", "r", encoding="utf-8") as file:
    data = json.load(file)

JSONファイルへ書く

1
2
3
4
user = {"name": "Yuna", "age": 28}

with open("user.json", "w", encoding="utf-8") as file:
    json.dump(user, file, ensure_ascii=False, indent=2)

今日のゴール

JSONはAPIとファイル保存の基本です。json.load、json.dump、json.loads、json.dumps の違いを意識して使いましょう。

この投稿は投稿者によって CC BY 4.0 の下でライセンスされています。