Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

json

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'

like image 201
janeh Avatar asked Dec 18 '12 17:12

janeh


People also ask

Why is JSON loads returning a list?

It can happen because your JSON is an array with a single object inside, for example, somebody serialized the Python list into JSON. So when you parse it, you get a list object in return.

Is JSON a list of dictionaries?

JSON, or JavaScript Object Notation, is a broader format used to encompass dictionary and list structures as shown in the image below. JSON: List and Dictionary Structure, Image by Author. The technical documentation says a JSON object is built on two structures: a list of key-value pairs and an ordered list of values.

Are Python dictionaries valid JSON?

Python has a library called json that allows you to convert JSON into dictionary and vice versa, write JSON data into a file, read JSON data from a file, among other things that we shall learn. Important methods in json : dumps(), dump(), load() and loads() .


1 Answers

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
like image 175
Andrew Clark Avatar answered Oct 03 '22 18:10

Andrew Clark