【问题标题】:How to parse json with python?如何用python解析json?
【发布时间】: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

【问题讨论】:

标签: python json parsing


【解决方案1】:

您在 JSON 结果的["children"] 上执行[0] 时只选择了一篇帖子。

因此,要获得所有个帖子,请不要使用[0]

reddit_posts = json.loads(f.read().decode("utf-8"))["data"]["children"]

现在您可以遍历所有这些:

for post in reddit_posts:
    print post["data"]["media"]["oembed"]["url"]

【讨论】:

  • 当我尝试得到一个 TypeError: 'NoneType' object is not subscriptable
  • 我可以在命令行中看到url,但是浏览器显示我上面提到的错误。
猜你喜欢
  • 2013-11-28
  • 2017-09-25
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多