2012-10-04 106 views
1

我試圖將一些API JSON數據導出到csv,但我只想要它的一些位。我試過row.append,但是我收到錯誤TypeError: string indices must be integers將python字典追加到csv

我是新來的蟒蛇,又有點困惑,爲什麼它要一個整數。

import urllib2 
import json 
import csv 

outfile_path='/NYTComments.csv' 

writer = csv.writer(open(outfile_path, 'w')) 

url = urllib2.Request('http://api.nytimes.com/svc/community/v2/comments/recent?api-key=ea7aac6c5d0723d7f1e06c8035d27305:5:66594855') 

parsed_json = json.load(urllib2.urlopen(url)) 

print parsed_json 

for comment in parsed_json['results']: 
    row = [] 
    row.append(str(comment['commentSequence'].encode('utf-8'))) 
    row.append(str(comment['commentBody'].encode('utf-8'))) 
    row.append(str(comment['commentTitle'].encode('utf-8'))) 
    row.append(str(comment['approveDate'].encode('utf-8'))) 
    writer.writerow(row) 

的parsed_json印刷看起來像這樣:

{u'status': u'OK', 
u'results': 
    {u'totalCommentsReturned': 25, 
    u'comments': 
     [{ 
      u'status': u'approved', 
      u'sharing': 0, 
      u'approveDate': u'1349378866', 
      u'display_name': u'Seymour B Moore', 
      u'userTitle': None, 
      u'userURL': None, 
      u'replies': [], 
      u'parentID': None, 
      u'articleURL': u'http://fifthdown.blogs.nytimes.com/2012/10/03/thursday-matchup-cardinals-vs-rams/', 
      u'location': u'SoCal', 
      u'userComments': u'api.nytimes.com/svc/community/v2/comments/user/id/26434659.xml', 
      u'commentSequence': 2, 
      u'editorsSelection': 0, 
      u'times_people': 1, 
      u'email_status': u'0', 
      u'commentBody': u"I know most people won't think this is a must watch game, but it will go a long way .... (truncated)", 
      u'recommendationCount': 0, 
      u'commentTitle': u'n/a' 
     }] 
    } 
} 
+1

評論字典?聽起來這可能是一個字符串。 – CrazyCasta

+0

該字典是parsed_json –

+0

是的,但它看起來像是將註釋視爲字典,如果它不是字典,那麼你有問題。 – CrazyCasta

回答

0
for comment in parsed_json['results']: #'comment' contains keys, not values 

應該

for comment in parsed_json['results']['comments']: 

parsed_json['results']本身是另一種解釋。

parsed_json['results']['comments']是要遍歷字典的名單。

+0

這也產生了這個錯誤: row.append(str(comment ['commentSequence']。encode('utf-8') )) TypeError:'int'對象不可訂閱 –

+0

即使樣本不是完整的輸出,您是否可以將'print parsed_json'的輸出添加到您的問題中? –

+0

謝謝。我已經做了。以上你可以看到一個評論的例子。 –

2

看起來像你犯了一個錯誤,我讓所有的時間。取而代之的

for comment in parsed_json['results']: 

你想

for comment_name, comment in parsed_json['results'].iteritems(): 

(或.items()如果你使用Python 3)。

只是遍歷字典(如parsed_json['results']大概是)給你的字典,而不是元素的。如果你這樣做

for thing in {'a': 1, 'b': 2}: 

然後thing將循環'a'和'b'。

然後,因爲關鍵顯然是一個字符串,你想這樣做"some_name"['commentSequence'],這是造成你所看到的錯誤消息。

dict.iteritems()另一方面,給你一個迭代器,它會給你一些元素,如('a', 1),然後('b', 2); for循環中的兩個變量然後分配給那裏的兩個元素,因此comment_name == 'a'comment == 1在這裏。

由於您似乎並未真正使用parsed_json['results']中的密鑰,因此您也可以循環for comment in parsed_json['results'].itervalues()

+0

你說得對,我想要的不是鑰匙。當我改變這一點時,我得到: TypeError:'int'對象不可訂閱 –