json --- JSON エンコーダおよびデコーダ がだいたいわかる最小の使用例を示す https://docs.python.org/ja/3/library/json.html
example.jsonを次のように用意する
{
"person1": {
"id": 10,
"name": "Gon",
"type": "Kyoka",
"weapon": "Ja Ja n Ken, Gu, Choki, Par"
},
"person2": {
"id": 20,
"name": "Killua",
"type": "Henka",
"weapon": "Jippu-jinrai, Kanmuru, Narukami"
},
"person3": {
"id": 30,
"name": "Kurapika",
"type": "Gugenka",
"weapon": "Judgement, Jail, etc chain."
}
}
次の例ではこのexample.jsonを読み込んでforを使ってkey, valueを表示し、新しいエントリを追加し、それをexample-out.jsonに書き出している。
#!/usr/bin/env python3
import os
import json
filename = 'example.json'
with open('example.json', 'r') as file:
obj = json.load(file)
for key in obj:
print(key, obj[key])
obj["person4"] = {
"id": 40,
"name": "Irumi",
"type": "So-sa",
"weapon": "Hari-ningyo"
}
name, ext = os.path.splitext(filename)
filename_out = os.path.join(name+'-out'+ext)
with open(filename_out, "w") as file:
json.dump(obj, file, indent=4)
ありがたいことに、JSONの記法とPythonのdictは表記が同じで書ける。indent=4
でヒューマンリーダブルなJSONを書き出せる。結果は次のようになる。
{
"person1": {
"id": 10,
"name": "Gon",
"type": "Kyoka",
"weapon": "Ja Ja n Ken, Gu, Choki, Par"
},
"person2": {
"id": 20,
"name": "Killua",
"type": "Henka",
"weapon": "Jippu-jinrai, Kanmuru, Narukami"
},
"person3": {
"id": 30,
"name": "Kurapika",
"type": "Gugenka",
"weapon": "Judgement, Jail, etc chain."
},
"person4": {
"id": 40,
"name": "Irumi",
"type": "So-sa",
"weapon": "Hari-ningyo"
}
}
以上!