在Python中导航多维JSON数组

DA *_*son 8 python json

我试图弄清楚如何在Python中查询JSON数组.有人可以告诉我如何通过一个相当复杂的数组进行简单的搜索和打印吗?

我正在使用的例子是:http://eu.battle.net/api/wow/realm/status

我想看看,例如,如何找到'Silvermoon'服务器,打印说'人口',然后是'Wintergrasp'阵列中的'控制派'.

该数组代码段目前如下所示:

{"type":"pve","population":"high","queue":false,"wintergrasp":{"area":1,"controlling-faction":0,"status":0,"next":1382350068792},"tol-barad":{"area":21,"controlling-faction":0,"status":0,"next":1382349141932},"status":true,"name":"Silvermoon","slug":"silvermoon","battlegroup":"Cyclone / Wirbelsturm","locale":"en_GB","timezone":"Europe/Paris"}
Run Code Online (Sandbox Code Playgroud)

目前我可以访问主数组,但似乎无法访问子数组而不将整个事件复制到另一个看起来很浪费的新变量.我希望能够做类似的事情

import urllib2
import json

req = urllib2.Request("http://eu.battle.net/api/wow/realm/status", None, {})
opener = urllib2.build_opener()
f = opener.open(req)

x = json.load(f)  # open the file and read into a variable

# search and find the Silvermoon server
silvermoon_array = ????

# print the population
print silvermoon_array.????

# access the Wintergrasp sub-array
wintergrasp_sub = ????
print wintergrasp_sub.????  # print the controlling-faction variable
Run Code Online (Sandbox Code Playgroud)

这真的可以帮助我掌握如何访问其他东西.

gon*_*opp 8

Python的交互模式是逐步探索结构化数据的好方法.很容易找到如何访问银月服务器数据:

>>> data=json.load(urllib2.urlopen("http://eu.battle.net/api/wow/realm/status"))
>>> type(data)
<type 'dict'>
>>> data.keys()
[u'realms']
>>> type(data['realms'])
<type 'list'>
>>> type(data['realms'][0])
<type 'dict'>
>>> data['realms'][0].keys()
[u'status', u'wintergrasp', u'battlegroup', u'name', u'tol-barad', u'locale', u'queue', u'timezone', u'type', u'slug', u'population']
>>> data['realms'][0]['name']
u'Aegwynn'
>>> [realm['name'] for realm in data['realms']].index('Silvermoon')
212
>>> silvermoon= data['realms'][212]
>>> silvermoon['population']
u'high'
>>> type(silvermoon['wintergrasp'])
<type 'dict'>
>>> silvermoon['wintergrasp'].keys()
[u'status', u'next', u'controlling-faction', u'area']
>>> silvermoon['wintergrasp']['controlling-faction']
>>> silvermoon['population']
u'high'
Run Code Online (Sandbox Code Playgroud)

如果您还不了解它们,您应该阅读dictionary.keys,list.indexlist comprehensions以了解正在发生的事情.

在确定数据结构之后,您最终可以重写数据访问,使其更具可读性和效率:

realms= data['realms']
realm_from_name= dict( [(realm['name'], realm) for realm in realms])
print realm_from_name['Silvermoon']['population']
print realm_from_name['Silvermoon']['wintergrasp']['controlling-faction']
Run Code Online (Sandbox Code Playgroud)

至于将数组复制到另一个浪费的变量,你应该知道python通过引用传递值.这意味着当您为新变量分配内容时不会涉及复制.这是一个简单的解释,即通过值传递和通过引用传递

最后,你似乎对表现过分担心.Python的理念是先把它弄好,然后再进行优化.如果你有正确的工作,如果你需要更好的性能,优化它,如果它是值得的时间.