【发布时间】:2011-08-29 23:29:10
【问题描述】:
我正在学习 Python 并尝试将 github 问题转换为可读形式。使用How can I convert JSON to 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) -
尝试使用方括号,(即 data = [json.load(f)] )