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'
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.
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.
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() .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With