- 1 year ago 84
JSON Question

For each loop with JSON object python

Alright, so I'm struggling a little bit with trying to parse my JSON object.
My aim is to grab the certain JSON key and return it's value.


"files": {
"resources": [
"name": "filename",
"hash": "0x001"
"name": "filename2",
"hash": "0x002"

I've developed a function which allows me to parse the JSON code above


def parsePatcher():
url = '{0}/{1}'.format(downloadServer, patcherName)
patch = urllib2.urlopen(url)
data = json.loads(
return data

Okay so now I would like to do a foreach statement which prints out each name and hash inside the
"resources": []

Foreach statement

for name, hash in patcher["files"]["resources"]:
print name
print hash

But it only prints out "name" and "hash" not "filename" and "0x001"

Am I doing something incorrect here?

Answer Source

By using name, hash as the for loop target, you are unpacking the dictionary:

>>> d = {"name": "filename",  "hash": "0x001"}
>>> name, hash = d
>>> name
>>> hash

This happens because iteration over a dictionary only produces the keys:

>>> list(d)
['name', 'hash']

and unpacking uses iteration to produce the values to be assigned to the target names.

That that worked at all is subject to random events even, on Python 3.3 and newer with hash randomisation enabled by default, the order of those two keys could equally be reversed.

Just use one name to assign the dictionary to, and use subscription on that dictionary:

for resource in patcher["files"]["resources"]:
    print resource['name']
    print resource['hash']