Python:JSON 字符串到字典列表 - 迭代时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13938183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: JSON string to list of dictionaries - Getting error when iterating
提问by janeh
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):
我正在将一个 JSON 字符串从 Objective-C 发送到 Python。然后我想将字符串的内容分解为 Python 列表。我正在尝试遍历一个字符串(现在是任何字符串):
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'
异常错误:“列表”对象没有属性“迭代”
采纳答案by Andrew Clark
Your JSON data is a list of dictionaries, so after json.loads(s)you will have jdataas a list, not a dictionary.
您的 JSON 数据是一个字典列表,因此json.loads(s)您将拥有jdata一个列表,而不是一个字典。
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
回答by Alexey Kachayev
json.loads(s)will return you list. To iterate over it you don't need iteritems.
json.loads(s)会回报你list。要迭代它,您不需要iteritems.
>>> jdata = json.loads(s)
>>> for doc in jdata:
... for key, value in doc.iteritems():
... print key, value
回答by xiyurui
for python 3.6 above, there has a little difference
对于上面的python 3.6,有一点不同
s = '[{"i":"imap.gmail.com","p":"someP@ss"},{"i":"imap.aol.com","p":"anoterPass"}]'
jdata = json.loads(s)
print (jdata)
for d in jdata:
for key, value in d.items():
print (key, value)
[{'i': 'imap.gmail.com', 'p': 'someP@ss'}, {'i': 'imap.aol.com', 'p': 'anoterPass'}]
i imap.gmail.com
p someP@ss
i imap.aol.com
p anoterPass

