ihue ihue - 3 months ago 14
Python Question

Access JSON Key in Python

I'm trying to print out all the

cpe_mac
fields of my JSON data.

I have



# Last updated : BH | 8/31/2016

import requests
import json

ssc_ip = raw_input("What is your SSC Host (Ex. http://172.19.242.32:1234/ ) ? : ")
if not ssc_ip:
ssc_ip = 'http://172.19.242.32:1234/'

cpe_num = raw_input("How many CPE(s) you want to delete ? : ")
print '\n'

url = ssc_ip+'vse/vcpes'
json_data = requests.get(url).json()
# print json_data

for x in json_data:
print json_data.cpe_mac





I kept getting

AttributeError: 'dict' object has no attribute 'cpe_mac'





Trying



print json_data['cpe_mac']


I got

KeyError: 'cpe_mac'

Answer

You have a nested dictionary, it should be:

for x in json_data['data']:
    print x['cpe_mac']
Comments