2

Google 스프레드 시트를 Python으로 가져와 JSON을 통해 처리하고 있습니다. 그것은 중간에 작동하고, 몇 시간 동안 Stackoverflow를보고 난 후에, 나는 질문을 할 시간이라고 생각합니다.Python에서 JSON 객체 반복 및 인쇄

예를 들어 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": "[email protected]"} 
    }], 
    "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": "[email protected]"} 
     }], 
     "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"}]}, 
    }] 
    } 
} 
다음과 같이

내 파이썬 코드는 다음과 같이 JSON 파일 출력의 최상위 계층 구조를 테스트

import requests, json 
r = requests.get('link-to-google-spreadsheet-json') 
j = r.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)이 올바르게 출력되도록하려면 어떻게해야합니까?

+0

Google 예제를 사용하여 JSON 파일 형식을 이미 게시 했으므로 feed -> entry -> title -> $ t에서 $ t 값을 얻으려는 시도를 볼 수 있습니다. – AAA

+0

나는 그것을 완전히 무시했다.> _> 나는 이전의 코멘트를 삭제했다. – Natan

답변

10

j [ 'feed']는 사전입니다.

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

감사합니다. 내가 만든 코드가 아니라 사전에 어떻게 접근했는지 설명해 주시겠습니까? – AAA

+0

j [ 'feed']를 반복 할 때, 키를 반복합니다 : category, updated, ... – sneawo

0

feedtitle이 사전은 목록이 없습니다 당신이 루프 그들에이해서는 안 : 같은 코드는 보일 것입니다. entry-list 용 for-loop가 하나만 있으면됩니다.