2015-06-19 117 views
1

如何獲取此函數以僅返回值「Accounting」?如何返回特定的json字段?

def getowner(): 
     z = [{u'_ref': u'network/ZG5zLm5ldHdvcmskMTAuMTAwLjEwMC4wLz90jLzA:10.100.100.0/24/default', u'extattrs': {u'Owner': {u'value': u'Accounting'}}}] 
     return ((h['value']) for h in z['Owner']) 


z = getowner() 
print z 

即時得到錯誤TypeError: list indices must be integers, not str

回答

3

z變量是一個數組因爲周圍的方括號(之一元素)。下面是我將如何訪問你所擁有的:

>>> z[0]['extattrs']['Owner']['value'] 
u'Accounting' 
1

更改您的代碼:

def getowner(): 
    z = [{u'_ref': u'network/ZG5zLm5ldHdvcmskMTAuMTAwLjEwMC4wLz90jLzA:10.100.100.0/24/default', u'extattrs': {u'Owner': {u'value': u'Accounting'}}}] 
    return z[0]['extattrs']['Owner']['value'] 

z = getowner() 
print z 
相關問題