問題
JSONファイル内のGigabitEthernet先頭要素のIPアドレスを192.168.1.2へ変更し、コンパクトなJSONと字下げしたJSONを別ファイルへ保存する。空欄[1]〜[4]へ入れる候補の順序はどれか。使用しない候補もある。
候補:① write、② loads、③ dumps、④ open、⑤ read
import json
with open("json ios xe.json", "r") as json_file:
json_file_content = json_file.[1]()
decoded_json = json.[2](json_file_content)
decoded_json['Cisco-IOS-XE-native:interface']['GigabitEthernet'][0]['ip']['address']['primary']['address'] = "192.168.1.2"
encoded_json_compact = json.[3](decoded_json)
encoded_json_indented = json.dumps(decoded_json, indent = 4)
with open("json ios xe compact.json", "w") as json_file:
json_file.[4](encoded_json_compact)
with open("json ios xe indented.json", "w") as json_file:
json_file.write(encoded_json_indented)
- A
⑤→②→③→①
- B
④→②→③→①
- C
⑤→③→②→①
- D
⑤→②→③→④
正解:A
理由
readでファイルの文字列を取得し、loadsでPythonの値へ変換する。値を変更した後、dumpsでJSON文字列へ戻し、writeでファイルへ保存する。indent=4は字下げを指定する。
選択肢ごとの説明
- A.
⑤→②→③→①
read→loads→dumps→writeにより、読取り、解析、値の変更、二通りのJSON保存という全処理がつながる。
- B.
④→②→③→①
ファイルオブジェクトにopenメソッドはなく、読取り文字列を取得できない。openはファイルを開く組込み関数である。
- C.
⑤→③→②→①
dumpsは文字列をPythonの辞書へ解析する関数ではない。loadsとdumpsの変換方向が逆になる。
- D.
⑤→②→③→④
最後の空欄はJSON文字列を既に開いたファイルへ書くwriteである。openで文字列を書き込むことはできない。