【问题标题】:Iterating and printing JSON objects in Python在 Python 中迭代和打印 JSON 对象
【发布时间】:2012-12-14 21:12:02
【问题描述】:

我有一个 Google 电子表格,我想用 Python 获取它,然后通过 JSON 处理它。工作到一半了,看了几个小时的Stackoverflow,我想是时候问一个问题了。

例如,JSON 文件的格式如下所示(来自https://developers.google.com/gdata/docs/json)。

{
  "version": "1.0",
  "encoding": "UTF-8",
  "feed": {
    "xmlns": "http://www.w3.org/2005/Atom",
    "xmlns$openSearch": "http://a9.com/-/spec/opensearchrss/1.0/",
    "xmlns$gd": "http://schemas.google.com/g/2005",
    "xmlns$gCal": "http://schemas.google.com/gCal/2005",
    "id": {"$t": "..."},
    "updated": {"$t": "2006-11-12T21:25:30.000Z"},
    "title": {
      "type": "text",
      "$t": "Google Developer Events"
    },
    "subtitle": {
      "type": "text",
      "$t": "The calendar contains information about upcoming developer 
       conferences at which Google will be speaking, along with other 
       developer-related events."
    },
    "link": [{
      "rel": "...",
      "type": "application/atom+xml",
      "href": "..."
      },{
      "rel": "self",
      "type": "application/atom+xml",
      "href": "..."
    }],
    "author": [{
      "name": {"$t": "Google Developer Calendar"},
      "email": {"$t": "developer-calendar@google.com"}
    }],
    "generator":{
      "version": "1.0",
      "uri": "http://www.google.com/calendar",
      "$t": "Google Calendar"
    },
    "openSearch$startIndex": {"$t": "1"},
    "openSearch$itemsPerPage": {"$t": "25"},
    "gCal$timezone": {"value": "America/Los_Angeles"},

    "entry": [{
      "id": {"$t": "..."},
      "published": {"$t": "2006-11-12T21:25:30.000Z"},
      "updated": {"$t": "2006-11-12T21:25:30.000Z"},
      "category": [{
        "scheme": "...",
        "term": "..."
      }],
      "title":{
        "type": "text",
        "$t": "WebmasterWorld PubCon 2006: Google Developer Tools in General"
      },
      "content": {
        "type": "text",
        "$t": "Google is sponsoring at
          <a href=\"http://www.pubcon.com/\">WebmasterWorld PubCon 2006</a>.
          \n Come and visit us at the booth or join us for an evening demo
          reception where we will be talking \"5 ways to enhance your website
          with Google Code\". \n After all, \n it is Vegas, baby! See you soon."
      },
      "link": [{
        "rel": "alternate",
        "type": "text/html",
        "href": "...",
        "title": "alternate"
        },{
        "rel": "self",
        "type": "application/atom+xml",
        "href": "..."
      }],
      "author": [{
        "name": {"$t": "Google Developer Calendar"},
        "email": {"$t": "developer-calendar@google.com"}
      }],
      "gd$transparency": {"value": "http://schemas.google.com/g/2005#event.opaque"},
      "gd$eventStatus": {"value": "http://schemas.google.com/g/2005#event.confirmed"},
      "gd$comments": {"gd$feedLink": {"href": "..."}},
      "gCal$sendEventNotifications": {"value": "true"},
      "gd$when": [{
        "startTime": "2006-11-15",
        "endTime": "2006-11-17",
        "gd$reminder": [{"minutes": "10"}]
      }],
      "gd$where": [{"valueString": "3150 Paradise Road,Las Vegas,NV 89109"}]},
    }]
  }
}

我的Python代码如下:

import requests, json
r = requests.get('link-to-google-spreadsheet-json')
j = r.json()

测试 JSON 文件输出的顶层层次结构如下:

>>> print j["version"]
1.0

但是遍历对象,像这样:

for feed in j["feed"]:
    for entry in feed["entry"]:
        for title in entry["title"]:
            print title["$t"]
        print
    print

给我以下错误:

Traceback (most recent call last):
File "<console>", line 2, in <module>
TypeError: string indices must be integers.

听起来它想从字符串中打印一个字母,只要我给出索引号。那么如何解析 JSON 以便它正确输出我想要的内容(例如,提要 -> 条目 -> 标题 -> $t)?

【问题讨论】:

  • 我已经使用 Google 的示例发布了 JSON 文件的格式,因此您可以看到我在尝试获取 $t 在 feed -> entry -> title -> $ 中的值t.
  • 我完全忽略了 >_> 我已经删除了我以前的 cmets。

标签: python json google-sheets google-spreadsheet-api python-requests


【解决方案1】:

feedtitle 是字典而不是列表,所以你不应该对它们进行 for 循环。您只需要一个用于条目列表的 for 循环。

【讨论】:

    【解决方案2】:

    j['feed'] 是一个字典。您的代码应如下所示:

    for entry in j['feed']['entry']:
        print entry['title']['$t']
    

    【讨论】:

    • 谢谢。你能解释一下我是如何访问字典而不是你生成的代码吗?
    • 当你迭代 j['feed'] 时,你会迭代它的键:category, updated, ...
    猜你喜欢
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多