【Python】JSONの扱い方

Pythonでは、JSONJavaScript Object Notation)データを扱うために組み込みのjsonモジュールが用意されている。

JSONの読み込み

JSONデータをPythonオブジェクトに変換するには、json.load()またはjson.loads()メソッドを利用する。

import json

# JSONファイルの読み込み
with open('data.json', 'r') as file:
    data = json.load(file)

# JSON文字列の読み込み
json_string = '{"name": "Takahashi", "age": 24}'
data = json.loads(json_string)

PythonオブジェクトからJSONへの変換

PythonオブジェクトをJSON形式の文字列に変換するには、json.dumps()またはjson.dump()メソッドを使用する。

import json

data = {'name': 'Takahashi', 'age': 24}
# PythonオブジェクトをJSONファイルに書き込む
with open('data.json', 'w') as file:
    json.dump(data, file)

# PythonオブジェクトをJSON文字列に変換
json_string = json.dumps(data)

JSONデータの操作

import json

# JSONデータの読み込み
with open('data.json', 'r') as file:
    data = json.load(file)

# JSONデータの操作
data['name'] = 'Tanaka'
data['age'] = 30

with open('data.json', 'w') as file:
    json.dump(data, file)