我正在学习python并试图将github问题转换为可读形式。使用有关如何将JSON转换为CSV的建议?我想出了这个:
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
我在这里想念什么?哪些是“字符串索引”?我确定一旦完成这项工作,我还会遇到更多问题,但是就目前而言,我只是希望它能正常工作!
当我将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)