問題 ccnp-350-401-topic-1-question-603・第3版

問題

次の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'}]
}

コード

  1. A 
    OutFile = open("devices.json", "w")
    json.dump(Devices, OutFile)
    OutFile.close()
    

    コード

  2. B 
    OutFile = open("devices.json", "w")
    OutFile.write(str(Devices))
    OutFile.close()
    

    コード

  3. C 
    with open("devices.json", "w") as OutFile:
        json.dumps(Devices)
    

    コード

  4. 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を保存する処理にもならない。

お問い合わせ

演習する →