Pythonでjsonをimportする方法は?

Pythonでjsonモジュールをインポートするためにimport jsonステートメントを使用し、その後、そのモジュール内の関数やクラスを使用してJSONデータを処理することができます。

以下はJSONモジュールのいくつかの一般的な関数やクラスの使用例です:

  1. JSON文字列をPythonオブジェクトに変換します。
import json

# JSON字符串
json_str = '{"name": "John", "age": 30, "city": "New York"}'
# 将JSON字符串转换为Python对象
python_obj = json.loads(json_str)
print(python_obj)  # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}
  1. PythonオブジェクトをJSON文字列に変換する。
import json

# Python对象
python_obj = {'name': 'John', 'age': 30, 'city': 'New York'}
# 将Python对象转换为JSON字符串
json_str = json.dumps(python_obj)
print(json_str)  # 输出: {"name": "John", "age": 30, "city": "New York"}
  1. JSONファイルを読み込んで、Pythonオブジェクトにパースする。
import json

# 读取JSON文件
with open('data.json') as json_file:
    json_str = json_file.read()
# 解析JSON字符串为Python对象
python_obj = json.loads(json_str)
print(python_obj)
  1. PythonオブジェクトをJSONファイルに書き込む。
import json

# Python对象
python_obj = {'name': 'John', 'age': 30, 'city': 'New York'}
# 将Python对象转换为JSON字符串
json_str = json.dumps(python_obj)
# 将JSON字符串写入文件
with open('data.json', 'w') as json_file:
    json_file.write(json_str)

これは、JSONモジュールの基本的な使用例です。JSONモジュールには、より複雑なJSONデータを扱うための他の関数やクラスも用意されています。詳細は公式ドキュメント「json – Python標準ライブラリドキュメント」を参照してください。

bannerAds