【ときどきpython】jsonライブラリを使う
jsonをpythonオブジェクトに変換(json.loads)
code:json.loads
import json
# JSONデータを変数に格納
json_data = '''
{
"name": "John",
"age": 30,
"city": "New York"
}
'''
# JSONデータを解析
parsed_data = json.loads(json_data)
# 解析されたデータを表示
print(parsed_data)
code:出力
{'name': 'John', 'age': 30, 'city': 'New York'}
pythonオブジェクトをjsonに変換(json.dumps)
code:json.dumps
import json
# Pythonの辞書
python_dict = {
"name": "John",
"age": 30,
"city": "New York"
}
# Python辞書をJSON文字列に変換
json_string = json.dumps(python_dict, indent=2)
# JSON文字列を表示
print(json_string)
code:出力
{
"name": "John",
"age": 30,
"city": "New York"
}
JSON形式のファイルからデータを読み込み、Pythonオブジェクトに変換(json.load)
code:test.json
{
"name": "John",
"age": 30,
"city": "New York"
}
code:json.load
import json
# json.loadを使用してファイルからデータを読み込む
with open("json/test.json", "r") as file:
data = json.load(file)
# 読み込んだデータを表示
print(data)