我正试图找出如何在Python中查询JSON数组。有人能告诉我如何做一个简单的搜索和打印通过一个相当复杂的数组请?
我使用的示例如下:http://eu.battle.net/api/wow/realm/status
例如,我想看看如何找到“Silvermoon”服务器,并打印出“population”,然后是“wintergrass”数组中的“controlling faction”。
数组片段当前如下所示:
{"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"}
目前,我可以访问主数组,但似乎无法访问子数组,而不将整个内容复制到另一个新变量,这似乎是浪费。我希望能做些
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
这将真正帮助我掌握如何访问其他东西。
Python的interactive mode是逐步探索结构化数据的好方法。很容易找到如何访问silvermoon服务器数据:
如果你还不知道它们,你应该阅读dictionary.keys、list.index和list comprehensions来了解发生了什么。
在确定了数据的结构之后,您最终可以重写数据访问,使其更具可读性和效率:
至于将数组复制到另一个变量是浪费,您应该知道python传递值by reference。这意味着当你给一个新变量赋值时不需要复制。Here's a simple explanation of passing by value vs passing by reference
最后,你似乎过分担心表现。Python的哲学是get it right first, optimize later。当工作正常时,如果需要更好的性能,则优化它(如果值得的话)。
这就是你想要的:
在Python中,
json.loads
将json对象映射到Python字典,并将Arrays
映射到list
,因此可以像使用常规Pythondict
和list
结构一样执行进一步的操作。以下是如何使用requests和
lamdbas
来完成此任务:相关问题 更多 >
编程相关推荐