我試圖將一些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'
}]
}
}
評論字典?聽起來這可能是一個字符串。 – CrazyCasta
該字典是parsed_json –
是的,但它看起來像是將註釋視爲字典,如果它不是字典,那麼你有問題。 – CrazyCasta