Soru

Zorluk: OrtaInterpreting JSON Encoded Data

A network automation script issues a RESTCONF HTTP GET request to a Cisco IOS XE router to inspect interface configurations. The API returns the following JSON response payload stored in a Python dictionary variable named `result`:

{
"ietf-interfaces:interfaces": {
"interface": [
{
"name": "Loopback0",
"description": "Router ID Interface",
"enabled": true,
"ietf-ip:ipv4": {
"address": [
{
"ip": "192.168.255.1",
"netmask": "255.255.255.255"
}
]
}
},
{
"name": "GigabitEthernet0/0/0",
"description": "WAN Link",
"enabled": false,
"ietf-ip:ipv4": {
"address": [
{
"ip": "10.0.12.1",
"netmask": "255.255.255.252"
}
]
}
}
]
}
}

Which Python expression correctly retrieves the IP address string `"10.0.12.1"` from the `result` dictionary?

  1. result["ietf-interfaces:interfaces"]["interface"][1]["ietf-ip:ipv4"]["address"][0]["ip"]Cevap
  2. B
    result["ietf-interfaces:interfaces"]["interface"][2]["ietf-ip:ipv4"]["address"][0]["ip"]
  3. C
    result["ietf-interfaces:interfaces"]["interface"][1]["ietf-ip:ipv4"]["address"]["ip"]
  4. D
    result["ietf-interfaces:interfaces"]["interface"]["GigabitEthernet0/0/0"]["ietf-ip:ipv4"]["address"][0]["ip"]

Cevap

The expression result["ietf-interfaces:interfaces"]["interface"][1]["ietf-ip:ipv4"]["address"][0]["ip"] correctly accesses the IPv4 address string.
The JSON structure contains nested dictionaries and lists. The key 'ietf-interfaces:interfaces' points to an object, whose 'interface' key points to a list of interface objects. 'GigabitEthernet0/0/0' is the second element in this list, which corresponds to index 1. Inside that interface dictionary, 'ietf-ip:ipv4' maps to another dictionary containing the key 'address'. The value of 'address' is a single-element list containing an IP configuration object, so index 0 is required before accessing the 'ip' string key.

Adım Adım Çözüm

1
Locate the top-level object key and the nested interface array.
Accessing result["ietf-interfaces:interfaces"]["interface"] yields a Python list containing two interface dictionary objects.
Brackets [...] in JSON denote arrays, which map to lists in Python.
2
Identify the index of GigabitEthernet0/0/0 within the interface array.
Loopback0 is at index 0, and GigabitEthernet0/0/0 is at index 1.
Python uses zero-based indexing for list items.
3
Traverse the nested dictionary keys and the address array.
Accessing ["ietf-ip:ipv4"]["address"] yields a list with one dictionary entry, accessed via index [0], followed by key ["ip"] to retrieve "10.0.12.1".
Since 'address' is enclosed in square brackets in the JSON structure, it must be indexed as a list before selecting the 'ip' key.

Anahtar Kavram

Interpreting nested JSON data structures (objects vs. arrays) and using zero-based Python indexing to extract key values.
Bu soruyu puanla