为什么我看到“类型错误:字符串索引必须是整数"? [英] Why am I seeing "TypeError: string indices must be integers"?
问题描述
我正在学习 python 并尝试将 github 问题转换为可读的形式.使用关于 如何将 JSON 转换为 CSV? 的建议我来了对此:
I'm playing with both learning python and trying to get github issues into a readable form. Using the advice on How can I convert JSON to CSV? I came up with this:
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 文件.当我尝试运行它时,我得到 p>
Where "issues.json" is the json file containing my github issues. When I try to run that, I get
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
我在这里错过了什么?哪些是字符串索引"?我敢肯定,一旦我开始工作,我会遇到更多问题,但就目前而言,我只想让它工作!
What am I missing here? Which are the "string indices"? I'm sure that once I get this working I'll have more issues, but for now , I'd just love for this to work!
当我将 for
语句调整为简单的
When I tweak the for
statement to simply
for item in data:
print item
我得到的是......问题"——所以我在做一些更基本的错误.这是我的一些json:
what I get is ... "issues" -- so I'm doing something more basic wrong. Here's a bit of my 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
时,它看起来很奇怪:
when I print data
it looks like it is getting munged really oddly:
{u'issues': [{u'body': u'Add missing paging (Older>>) lin...
推荐答案
item
很可能是代码中的一个字符串;字符串索引是方括号中的索引,例如 gravatar_id
.所以我首先检查你的 data
变量,看看你在那里收到了什么;我猜 data
是一个字符串列表(或者至少是一个包含至少一个字符串的列表),而它应该是一个字典列表.
item
is most likely a string in your code; the string indices are the ones in the square brackets, e.g., gravatar_id
. So I'd first check your data
variable to see what you received there; I guess that data
is a list of strings (or at least a list containing at least one string) while it should be a list of dictionaries.
这篇关于为什么我看到“类型错误:字符串索引必须是整数"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!