【发布时间】:2012-10-14 21:50:56
【问题描述】:
我正在尝试使用 python 解析一些 json 数据,但在遍历不同的项目时遇到了麻烦。看起来所有数据都在一个列表中,并且整个列表中的每个项目都有一个不同的字典。这是我目前所拥有的:
try:
f = urllib.urlopen("http://www.reddit.com/r/videos/top/.json");
except Exception:
print("ERROR: malformed JSON response from reddit.com")
reddit_posts = json.loads(f.read().decode("utf-8"))["data"]["children"][0]
print reddit_posts["data"]["media"]["oembed"]["url"]
我可以显示第一个 url,但我不确定如何迭代所有项目并显示 url。有什么建议吗?
另外,这是我尝试解析的 json 格式更好的视图:http://jsonviewer.stack.hu/#http://www.reddit.com/r/videos/top/.json
编辑: 我尝试了 for 循环,但无法实现它。
for entry in reddit_posts:
print entry[0] #only prints the first character of entry ('k' and 'd')
print entry["data"] #get an error: string indices must be integers
【问题讨论】:
-
@Blender 我尝试在其中放入一个 for 循环(它在编辑中),但这样做时遇到了麻烦