【问题标题】:Python Json ParsingPython Json 解析
【发布时间】:2011-06-20 10:27:00
【问题描述】:

我在使用 json 库用 python 解析 json 时遇到了一点问题。 这是我要解析的 json 格式:

{'entry':[
    {

        JSON Data 1
    }, 

        JSON Data 2
    }
]}

这是我的 Python:

for entry in response['entry'][0]:

    video['video_url'] = entry['id']['$t']
    video['published'] = entry['published']['$t']

我似乎无法使用上面的代码遍历 JSON 的两个块,由于某种原因,我只输出了第一个块。

有人有什么想法吗?提前致谢。

【问题讨论】:

  • 您的 JSON 中似乎缺少 {。 (好像你会在 Python 中缺少一个括号。)

标签: python json parsing


【解决方案1】:

如果:

response = {'entry':[
    {

        JSON Data 1
    }, 
    {

        JSON Data 2
    }
]}

还有:

response['entry'][0] == { JSON Data 1  }

然后:

for entry in response['entry']:

    video['video_url'] = entry['id']['$t']
    video['published'] = entry['published']['$t']

或者:

video = dict(zip(['video_url', 'published'], [entry['id']['$t'], entry['published']['$t']]) for entry in response['entry']

【讨论】:

  • 不,只返回第一个块:-/感谢您的帮助
  • 响应['entry'][0] == { JSON 数据 1 }, {JSON 数据 2}
  • 好的,您能否详细告诉我们您的意见,以便我们了解您真正需要什么? response['entry'][0] == { JSON Data 1 }, {JSON Data 2} 还是 response['entry'][0] == [{ JSON Data 1 }, {JSON Data 2}]?跨度>
【解决方案2】:

该列表包含 2 个单独的字典。直接遍历列表。

【讨论】:

  • 你能举个例子吗?
  • for foo in [1, 2, 3]: do_something(foo)
猜你喜欢
  • 2012-01-03
  • 1970-01-01
  • 2019-08-11
  • 2013-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-29
相关资源
最近更新 更多