JSON データの操作
JSON モジュールを適切にインポートする方法がわかったので、一般的な JSON 操作にどのように使用するかを見ていきましょう。
完全な JSON 例の作成
json_operations.py という名前の新しいファイルを作成し、次の内容を記述します。
## Complete example of working with JSON in Python
import json
## 1. Converting Python object to JSON string (serialization)
user = {
"name": "Charlie",
"age": 28,
"is_student": False,
"courses": ["Python", "Data Science", "Web Development"],
"address": {
"street": "123 Tech Lane",
"city": "Boston",
"zipcode": "02101"
}
}
## Convert Python dictionary to JSON string
json_string = json.dumps(user, indent=2)
print("JSON string created from Python object:")
print(json_string)
print("\n" + "-"*50 + "\n")
## 2. Parse JSON string to Python object (deserialization)
parsed_user = json.loads(json_string)
print("Python object created from JSON string:")
print("Name:", parsed_user["name"])
print("Age:", parsed_user["age"])
print("Courses:", parsed_user["courses"])
print("City:", parsed_user["address"]["city"])
print("\n" + "-"*50 + "\n")
## 3. Writing JSON to a file
with open("/home/labex/project/user_data.json", "w") as json_file:
json.dump(user, json_file, indent=2)
print("JSON data written to user_data.json")
## 4. Reading JSON from a file
with open("/home/labex/project/user_data.json", "r") as json_file:
loaded_user = json.load(json_file)
print("JSON data loaded from file. User name:", loaded_user["name"])
このスクリプトは、4 つの一般的な JSON 操作を示しています。
json.dumps() を使用して Python オブジェクトを JSON 文字列に変換する
json.loads() を使用して JSON 文字列を Python オブジェクトに解析する
json.dump() を使用して JSON データをファイルに書き込む
json.load() を使用してファイルから JSON データを読み込む
スクリプトを実行します。
python3 /home/labex/project/json_operations.py
次のような出力が表示されるはずです。
JSON string created from Python object:
{
"name": "Charlie",
"age": 28,
"is_student": false,
"courses": [
"Python",
"Data Science",
"Web Development"
],
"address": {
"street": "123 Tech Lane",
"city": "Boston",
"zipcode": "02101"
}
}
--------------------------------------------------
Python object created from JSON string:
Name: Charlie
Age: 28
Courses: ['Python', 'Data Science', 'Web Development']
City: Boston
--------------------------------------------------
JSON data written to user_data.json
JSON data loaded from file. User name: Charlie
このスクリプトは、user_data.json という名前のファイルも作成しました。その内容を見てみましょう。
cat /home/labex/project/user_data.json
適切なインデントでフォーマットされた JSON データが表示されるはずです。
{
"name": "Charlie",
"age": 28,
"is_student": false,
"courses": ["Python", "Data Science", "Web Development"],
"address": {
"street": "123 Tech Lane",
"city": "Boston",
"zipcode": "02101"
}
}
これで、モジュールを適切にインポートすることにより、NameError: name 'json' is not defined エラーを回避する方法を含め、Python で JSON データを操作する方法を正常に学習しました。