問題
次のDevicesのデータ構造をJSONファイルへ保存するPythonコードはどれか。
import json
Devices = {'Switches': [{'name': 'AccSw1',
'ip': '2001:db8:4308:3884:3::1'},
{'name': 'AccSw2',
'ip': '2001:db8:12b1:31a7:fffe::2'}],
'Routers': [{'name': 'CE1', 'ip': '2001:db8:31ac:a97a:8::1'},
{'name': 'CE2', 'ip': '2001:db8:7ac8:9ab7::2'}]
}

- A
OutFile = open("devices.json", "w") json.dump(Devices, OutFile) OutFile.close()
- B
OutFile = open("devices.json", "w") OutFile.write(str(Devices)) OutFile.close()
- C
with open("devices.json", "w") as OutFile: json.dumps(Devices)
- D
with open("devices.json", "w") as OutFile: Devices = json.load(OutFile)
正解:A
理由
json.dumpはPythonの値をJSONへ変換してファイルへ書く。json.dumpsはJSON文字列を返すため、保存にはその文字列を書き込む処理が必要になる。
選択肢ごとの説明
- A.
OutFile = open("devices.json", "w") json.dump(Devices, OutFile) OutFile.close()
書込み用ファイルへjson.dumpでDevicesをJSONとして保存し、closeで閉じる。
- B.
OutFile = open("devices.json", "w") OutFile.write(str(Devices)) OutFile.close()
strはPythonの辞書の文字列表現を作る。この辞書の一重引用符などはJSONの構文にならない。
- C.
with open("devices.json", "w") as OutFile: json.dumps(Devices)
json.dumpsの返り値をファイルへ書いていないため、wで開いたファイルは空のままである。
- D.
with open("devices.json", "w") as OutFile: Devices = json.load(OutFile)
json.loadはファイルからJSONを読み取る処理である。wで開いたファイルは読み取れず、Devicesを保存する処理にもならない。