0

How do i get the speed value out of this in code?

{
  "response": {
    "speed": "1000000",
    "lastUpdated": "2018-10-09 11:19:10.981000",
    "portMode": "access",
    "portType": "Ethernet Port",
    "description": " changed by DNAC",
    "series": "Cisco Catalyst 9300 Series Switches",
    "ifIndex": "31",
    "mediaType": "100/1000/2.5G/5G/10GBaseTX",
    "className": "SwitchPort",
    "interfaceType": "Physical",
    "ipv4Address": null,
    "ipv4Mask": null,
    "isisSupport": "false",
    "mappedPhysicalInterfaceId": null,
    "mappedPhysicalInterfaceName": null,
    "nativeVlanId": "1",
    "ospfSupport": "false",
    "pid": "C9300-24UX",
    "serialNo": "FCW2140L039",
    "voiceVlan": null,
    "status": "up",
    "deviceId": "4757da48-3730-4833-86db-a0ebfbdf0009",
    "macAddress": "f8:7b:20:71:4d:98",
    "portName": "TenGigabitEthernet1/0/24",
    "adminStatus": "UP",
    "duplex": "FullDuplex",
    "vlanId": "1",
    "instanceTenantId": "5b13fcf9651f93008acd0702",
    "instanceUuid": "8beed342-3718-4fa9-8377-4c7d94c77aef",
    "id": "8beed342-3718-4fa9-8377-4c7d94c77aef"
  },
  "version": "1.0"
}

I tried the code below but it does not work.

for items in data["response"] print(items['speed'])

this wil give me the error TypeError: string indices must be integers

  • 3
    just `data["response"]["speed"]` – Jean-François Fabre Oct 09 '18 at 11:58
  • Low quality dupe candidate for a low quality question: [Python - accessing values nested within dictionaries](//stackoverflow.com/q/11700798) – Aran-Fey Oct 09 '18 at 12:04
  • @Aran-Fey you're too kind with me. Just close and I'll delete my answer next time :) – Jean-François Fabre Oct 09 '18 at 12:15
  • @Jean-FrançoisFabre Well, I'm not very happy with that question as a dupe target, to be honest. The question is kind of unclear, so the answers are all over the place. And there's some value in explaining why the OP's code throws a TypeError, too. So, overall, posting an answer was a reasonable choice IMO. – Aran-Fey Oct 09 '18 at 12:23

1 Answers1

0

The for item in data['response'] iterates through a dict. In python, when you iterate though a dict, you iterate through its keys only. So, each item is a string, hence the error.

In your case, you can directly write

data['response']['speed']
blue_note
  • 27,712
  • 9
  • 72
  • 90