janehouse janehouse - 20 days ago 5
JSON Question

Python: JSON string to list of dictionaries - Getting error when iterating

I am sending a JSON string from Objective-C to Python. Then I want to break contents of the string into a Python list. I am trying to iterate over a string (any string for now):

import json

s = '[{"i":"imap.gmail.com","p":"someP@ss"},{"i":"imap.aol.com","p":"anoterPass"}]'
jdata = json.loads(s)
for key, value in jdata.iteritems():
print key, value


I get this error:


Exception Error: 'list' object has no attribute 'iterates'

Answer

Your JSON data is a list of dictionaries, so after json.loads(s) you will have jdata as a list, not a dictionary.

Try something like the following:

import json

s = '[{"i":"imap.gmail.com","p":"someP@ss"},{"i":"imap.aol.com","p":"anoterPass"}]'
jdata = json.loads(s)
for d in jdata:
    for key, value in d.iteritems():
        print key, value