【发布时间】:2012-09-26 00:58:59
【问题描述】:
我正在尝试将一些 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'
}]
}
}
【问题讨论】:
-
comment 是字典吗?听起来它可能是一个字符串。
-
字典已解析_json
-
是的,但是您似乎将评论视为字典,如果它不是字典,那么您就有问题了。
标签: python json csv dictionary