stat.us stat.us - 3 months ago 12
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.

JSON File

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


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

Function

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


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

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

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

>>> d = {"name": "filename",  "hash": "0x001"}
>>> name, hash = d
>>> name
'name'
>>> hash
'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']
Comments