• In the previous lesson, you learned to read Python data structures by hand.
    Now you need a library to fetch them from a router. The most common one is requests.

    It handles opening the HTTPS connection, sending the request, and returning the response:

    import requests
    
    response = requests.get("https://192.168.1.1/restconf/data/...")

    The data inside that response arrives in JSON.
    Two specific details in this section trip up candidates on the exam.

    JSON vs Python Dict

    When Python talks to a Cisco device, both sides exchange data as JSON text.
    JSON looks almost identical to a Python dictionary, with three key differences:

    {
        "hostname": "R1",
        "port": 830,
        "enabled": true,
        "interfaces": ["Gi0/0", "Gi0/1"]
    }

    Rule

    JSON

    Python

    String quotes

    Always double quotes

    Single or double quotes

    Booleans

    true / false

    True / False

    Null value

    null

    None

    Table 1 – JSON vs Python syntax

    If an exam snippet uses single quotes or capitalized True inside JSON, it is invalid syntax.

    Answer the question below

    Is { "name": "R1", "alive": True } valid JSON? (yes or no)

    Response Parsing

    When your script receives JSON from a device, the data arrives as a plain text string. You cannot index a string by key, so you convert it into a Python dict first:

    import requests
    
    response = requests.get(url)
    
    print(type(response.text))
    print(type(response.json()))

    Output:

    <class 'str'>
    <class 'dict'>
    • response.text: Returns raw JSON string. Indexing with key names like response.text["hostname"] crashes.

    • response.json(): Parses the JSON string and returns a Python dictionary you can index normally.

    You have

    You get

    You can do

    response.text

    string

    String operations only

    response.json()

    dict

    Index with ["key"], loop, slice

    json.loads(text)

    dict

    Same as response.json()

    json.dumps(d)

    string

    Convert a Python dict back to a JSON string (for sending)

    Table 2 – Working with JSON in your script

    40 % Complete: you’re making great progress

    Ready to pass your CCNP exam?