我在玩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...
你缺少的是'print repr(data)'或'import pprint; pprint.pprint(data)' – 2011-05-20 21:22:43
@IbrahimApachi錯誤的問題。 :) – Amanda 2015-12-02 19:33:07