Navigating Multi-Dimensional JSON arrays in Python

2024/10/15 19:23:24

I'm trying to figure out how to query a JSON array in Python. Could someone show me how to do a simple search and print through a fairly complex array please?

The example I'm using is here: http://eu.battle.net/api/wow/realm/status

I'd like to see, for example, how to find the 'Silvermoon' server, and print say its 'population', then the 'controlling-faction' within the 'Wintergrasp' array.

The array snippet currently looks like this:

{"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"}

At the moment I can access the main array, but don't seem to be able to access sub-arrays without copying the whole thing to another new variable which seems wasteful. I'd like to be able to do something like

import urllib2
import jsonreq = 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

This would really help me get to grips with how to access other things.

Answer

Python's interactive mode is a great way to progressively explore structured data. It's easy to find how to access, say, the silvermoon server data:

>>> 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'

If you don't know about them yet, you should read up on dictionary.keys, list.index and list comprehensions to understand what's going on.

After figuring out the structure of the data, you can finally rewrite the data access to be a bit more readable and efficient:

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']

As to copying the array to another variable being wasteful, you should know that python passes value by reference. That means that there's no copying involved when you assign something to a new variable. Here's a simple explanation of passing by value vs passing by reference

Finally, you seem to be excessively worried with performance. Python's philosophy is get it right first, optimize later. When you have this working correctly and if you need better performance, optimize it, if it's worth the time.

https://en.xdnf.cn/q/69249.html

Related Q&A

Numpy, apply a list of functions along array dimension

I have a list of functions of the type:func_list = [lambda x: function1(input),lambda x: function2(input),lambda x: function3(input),lambda x: x]and an array of shape [4, 200, 200, 1] (a batch of image…

Database first Django models

In ASP.NET there is entity framework or something called "database first," where entities are generated from an existing database. Is there something similar for Django? I usually work with …

How to use pythons Structural Pattern Matching to test built in types?

Im trying to use SPM to determine if a certain type is an int or an str. The following code: from typing import Typedef main(type_to_match: Type):match type_to_match:case str():print("This is a St…

Importing app when using Alembic raises ImportError

I am trying to study how to use alembic in flask, I want to import a method in flask app:tree . . ├── README.md ├── alembic │ ├── README │ ├── env.py │ ├── env.pyc │ ├── s…

Git add through python subprocess

I am trying to run git commands through python subprocess. I do this by calling the git.exe in the cmd directory of github.I managed to get most commands working (init, remote, status) but i get an err…

How to unread a line in python

I am new to Python (2.6), and have a situation where I need to un-read a line I just read from a file. Heres basically what I am doing.for line in file:print linefile.seek(-len(line),1)zz = file.readli…

typeerror bytes object is not callable

My code:import psycopg2 import requests from urllib.request import urlopen import urllib.parse uname = " **** " pwd = " ***** " resp = requests.get("https://api.flipkart.net/se…

How to inverse lemmatization process given a lemma and a token?

Generally, in natural language processing, we want to get the lemma of a token. For example, we can map eaten to eat using wordnet lemmatization.Is there any tools in python that can inverse lemma to a…

NameError: name N_TOKENS is not defined

I am new on Python and just got around to install PyCharm for Windows. Downloaded some sample code from Skype for testing their SkypeKit API. But... As soon as I hit the debug button, I get this: (I ha…

Moving Spark DataFrame from Python to Scala whithn Zeppelin

I created a spark DataFrame in a Python paragraph in Zeppelin.sqlCtx = SQLContext(sc) spDf = sqlCtx.createDataFrame(df)and df is a pandas dataframeprint(type(df)) <class pandas.core.frame.DataFrame&…