Question

Difficulty: MediumInterpreting JSON Encoded Data

A network administrator parses a JSON response payload from a Cisco Catalyst Center API call stored in a Python dictionary variable named `inventory_data`:

{
"response": [
{
"hostname": "Core-SW-01",
"platformId": "C9300-48U",
"upTimeMinutes": 21600,
"stackMembers": ["Core-SW-01A", "Core-SW-01B"]
},
{
"hostname": "Dist-SW-01",
"platformId": "C9200-24P",
"upTimeMinutes": 61200,
"stackMembers": ["Dist-SW-01A"]
}
],
"version": "1.0"
}

Which Python expression correctly extracts the string value `'Core-SW-01B'` from the payload?

  1. inventory_data["response"][0]["stackMembers"][1]Answer
  2. B
    inventory_data["response"][1]["stackMembers"][0]
  3. C
    inventory_data["response"][0]["stackMembers"][2]
  4. D
    inventory_data["response"]["hostname"]["Core-SW-01"]["stackMembers"][1]

Answer

inventory_data["response"][0]["stackMembers"][1]
The key 'response' maps to a JSON array (list). The first element at index 0 is the object representing the device 'Core-SW-01'. Within this object, the key 'stackMembers' holds another array of strings. Because Python lists use zero-based indexing, the second item 'Core-SW-01B' is located at index 1. Therefore, `inventory_data["response"][0]["stackMembers"][1]` correctly extracts the target value.

Step-by-Step Solution

1
Locate the outer key pointing to the target array
`inventory_data["response"]` yields a list of dictionary objects representing switches.
The root object contains a top-level key named 'response'.
2
Select the correct switch object from the list using 0-based indexing
`inventory_data["response"][0]` selects the first dictionary object containing 'Core-SW-01'.
Python list indices start at 0, making index 0 the target for the first switch in the response array.
3
Navigate to the nested array and select the target element
`inventory_data["response"][0]["stackMembers"][1]` evaluates to 'Core-SW-01B'.
Accessing key 'stackMembers' returns a list, and index 1 retrieves the second element within that list.

Key Concept

JSON Array and Object Traversal using Python Indexing
Estimated Time:1m 15s
Rate this question