0

I am using the Service Now Rest API to retrieve information on a server which is being returned as a JSON response which I am decoding into a python3 dictionary so I can pull out specific items further down in my code, but I am having trouble understanding how to use what appears to be a nested dictionary that is created from the JSON. Can someone please help me understand how to extract specific values from the dictionary. See below an example of what comes back (shortened).

#! /usr/bin/python3

# Include required libraries
import requests

# Set the request parameters
url = 'https://example.service-now.com/api/now/table/cmdb_ci_server'
user = 'example'
pwd = 'example'

# Set proper headers
headers = {"Content-Type":"application/json","Accept":"application/json"}

# Do the HTTP request
response = requests.get(url, auth=(user, pwd), headers=headers )

# Check for HTTP codes other than 200
if response.status_code != 200:
    print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:',response.json())
    exit()

# Decode the JSON response into a dictionary and use the data
data = response.json()

print(data)

Here is an example of the response (shortened)

{
  "result": [
    {
      "u_raid": "",
      "u_pir_required": "false",
      "u_original_system": "",
      "u_backup_pool": "vsdfnvjsv",
      "u_virtual_ip": "",
      "cpu_speed": "",
      "u_vendor": "",
      "u_lun_tier": "",
      "cost_center": {
        "link": "cdncdnckidnicsw",
        "value": "vfevfdbvfdsbvsdf"
      },
      "dns_domain": "",
      "u_vio2": "",
      "fault_count": "0",
      "u_hardware_type": "",
      "host_name": ""
    }
  ]
}

I have tried the following after working through a few nested dictionary tutorials, but I am not having much luck.

print(data['result']['u_backup_pool'])

TypeError: list indices must be integers or slices, not str

Atomiklan
  • 5,164
  • 11
  • 40
  • 62

1 Answers1

1

The value for key 'result' is a list (notice the square brackets) with one item, try print(data['result'][0]['u_backup_pool'])

Manu Valdés
  • 2,343
  • 1
  • 19
  • 28
  • Thank you! Now I understand! – Atomiklan Jan 22 '20 at 10:54
  • @Atomiklan Note that since it's a list, this suggests that there may be *more than one* dict within it (or perhaps even none). You should probably *loop* over the list using `for .. in ..`… – deceze Jan 22 '20 at 10:56
  • Thank you for the help. Now that I see whats going on, it makes a lot more sense. – Atomiklan Jan 22 '20 at 10:59