2011-05-20 89 views
81

我在玩Python和學習python,並試圖將github問題變爲可讀形式。在How can I convert JSON to CSV?使用意見,我想出了這一點:爲什麼我看到「TypeError:字符串索引必須是整數」?

import json 
import csv 

f=open('issues.json') 
data = json.load(f) 
f.close() 

f=open("issues.csv","wb+") 
csv_file=csv.writer(f) 

csv_file.writerow(["gravatar_id","position","number","votes","created_at","comments","body","title","updated_at","html_url","user","labels","state"]) 

for item in data: 
     csv_file.writerow([item["gravatar_id"], item["position"], item["number"], item["votes"], item["created_at"], item["comments"], item["body"], item["title"], item["updated_at"], item["html_url"], item["user"], item["labels"], item["state"]]) 

其中「issues.json」是包含我的github問題JSON文件。當我嘗試運行時,我得到

File "foo.py", line 14, in <module> 
csv_file.writerow([item["gravatar_id"], item["position"], item["number"], item["votes"], item["created_at"], item["comments"], item["body"], item["title"], item["updated_at"], item["html_url"], item["user"], item["labels"], item["state"]]) 

TypeError: string indices must be integers 

我在這裏錯過了什麼?哪些是「字符串索引」?我確信,一旦我得到這個工作,我會有更多的問題,但現在,我只是喜歡這個工作!

UPDATE: 當我捏捏for語句簡單

for item in data: 
    print item 

什麼,我得到的是......「問題」 - 所以我做一些更基本的錯誤。這是一個有點我的JSON的:

{"issues":[{"gravatar_id":"44230311a3dcd684b6c5f81bf2ec9f60","position":2.0,"number":263,"votes":0,"created_at":"2010/09/17 16:06:50 -0700","comments":11,"body":"Add missing paging (Older>>) links... 

當我打印data它看起來是越來越被改寫的真的很奇怪:

{u'issues': [{u'body': u'Add missing paging (Older>>) lin... 
+0

你缺少的是'print repr(data)'或'import pprint; pprint.pprint(data)' – 2011-05-20 21:22:43

+0

@IbrahimApachi錯誤的問題。 :) – Amanda 2015-12-02 19:33:07

回答

45

item是最有可能在你的代碼串;字符串索引是方括號中的字符串索引,例如gravatar_id。所以我首先檢查你的data變量,看看你在那裏收到了什麼;我猜data是一個字符串列表(或至少包含至少一個字符串的列表),而它應該是一個字典列表。

75

變量item是一個字符串。索引看起來像這樣:

>>> mystring = 'helloworld' 
>>> print mystring[0] 
'h' 

上面的示例使用0索引的字符串來表示第一個字符。

字符串不能有字符串索引(就像字典一樣)。所以這是行不通的:

>>> mystring = 'helloworld' 
>>> print mystring['stringindex'] 
TypeError: string indices must be integers 
18

datadict對象。所以,遍歷這樣的:

的Python 2

for key, value in data.iteritems(): 
    print key, value 

的Python 3

for key, value in data.items(): 
    print(key, value) 
-1

如果一個共同的丟失會發生這種情況。當我有一個兩元組列表時,我碰到了它,每個元組都由第一個位置的字符串和第二個位置的列表組成。在一個案例中,我錯誤地忽略了一個元組的第一個元素之後的逗號,而解釋者認爲我試圖索引第一個元素。

相關問題