2016-08-31 44 views
-2

我试图打印出JSON数据的所有cpe_mac字段。在Python中访问JSON密钥

# 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 

我一直得到

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


试图

print json_data['cpe_mac']

KeyError: 'cpe_mac'

+1

。此外,您正在遍历'json_data',但不使用迭代对象。 –

+1

你需要使用字典符号:'json_data ['cpe_mac']'但是你期待'x'做什么? –

+0

@ TadhgMcDonald-Jensen:是的,我得到了'KeyError:'cpe_mac'' – ihue

回答

3

你有一个嵌套的字典,它应该是:

for x in json_data['data']: 
    print x['cpe_mac'] 
那不是你如何访问字典键
+0

您的答案完美无瑕! :) – ihue

+1

@ihue ..这是Python 101讲座:)... ...字典基础知识,你需要看看你的数据格式,所以你可以得到正确的价值,你正在寻找。 –

1

这不是如何访问字典项。感兴趣的字典包含在父字典json_data内的列表中(可通过键data访问)。

你应该这样做:

for x in json_data['data']: 
    print x['cpe_mac'] 
+0

我得到了'TypeError:字符串索引必须是整数'... – ihue

+0

这是一个嵌套的字典.. –

+0

@IronFist嵌套在父字典'json_data'中的列表中(在键'data'处) –