我正在尝试将一些 API JSON 数据导出到 csv,但我只想要其中的一些。我试过row.append
了,但我得到了错误TypeError: string indices must be integers
。
我是 python 新手,对于它为什么需要一个整数有点困惑。
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'
}]
}
}