問題 ccnp-350-401-topic-1-question-508-v-6bf619b3・第3版

問題

次のスクリプトで変更したインターフェース設定を、設定オブジェクトを表すJSON文書のままローカルファイルへ保存する。追加するコードはどれか。

import json
import requests
Creds = ("user", "Z#419010526SmnV")
Headers = {"Content-Type": "application/yang-data+json",
           "Accept": "application/yang-data+json"}
BaseURL = "https://cpe/restconf/data"
URL = BaseURL + "/Cisco-IOS-XE-native:native/interface"
Response = requests.get(URL, auth=Creds, headers=Headers, verify=False)
UpdatedConfig = Response.text.replace("2001:db8:1:", "2001:db8:cafe:")
  1. A 
    OutFile = open("ifaces.json", "w")
    OutFile.write(Response.text)
    OutFile.close()
    
  2. B 
    OutFile = open("ifaces.json", "w")
    OutFile.write(UpdatedConfig)
    OutFile.close()
    
  3. C 
    OutFile = open("ifaces.json", "w")
    json.dump(UpdatedConfig, OutFile)
    OutFile.close()
    
  4. D 
    OutFile = open("ifaces.json", "w")
    OutFile.write(Response.json())
    OutFile.close()
    

正解:B

理由

Response.text.replaceの結果はstrである。JSON文書を含む文字列をそのままファイルへ書くと、変更後の設定文書を保存できる。json.dumpはstrも受け付けるが、文書の文字列値として再符号化する。

選択肢ごとの説明

A.
OutFile = open("ifaces.json", "w")
OutFile.write(Response.text)
OutFile.close()

変更前の応答文字列を書くため、UpdatedConfigで行ったIPv6プレフィックスの置換が保存されない。

B.
OutFile = open("ifaces.json", "w")
OutFile.write(UpdatedConfig)
OutFile.close()

変更後のJSON文書を含む文字列をそのまま書き込み、置換した設定を保存する。

C.
OutFile = open("ifaces.json", "w")
json.dump(UpdatedConfig, OutFile)
OutFile.close()

UpdatedConfigはstrなので、JSON文字列値として引用符やエスケープを付けて符号化する。設定オブジェクトのJSON文書をそのまま保存する操作とは異なる。

D.
OutFile = open("ifaces.json", "w")
OutFile.write(Response.json())
OutFile.close()

json()が返すPythonの辞書やリストをwriteへ直接渡すことはできず、変更後のUpdatedConfigも使用していない。

お問い合わせ

演習する →