2012-10-04 104 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'对象不可订阅 –