如何返回特定的json字段?

时间:2015-06-19 14:20:13

标签: python 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

2 个答案:

答案 0 :(得分:3)

由于周围的方括号,您的z变量是一个数组(由一个元素组成)。以下是我访问你所拥有的内容的方法:

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

答案 1 :(得分: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