python - 为什么我看到 "TypeError: string indices must be

我正在学习 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...

最佳答案

变量item 是一个字符串。索引如下所示:

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

上面的例子使用字符串的0索引来引用第一个字符。

字符串不能有字符串索引(就像字典一样)。所以这行不通:

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

关于python - 为什么我看到 "TypeError: string indices must be integers"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6077675/

相关文章:

php - json_encode() 转义正斜杠

python - 将类实例序列化为 JSON

javascript - 在 JavaScript 中将 JSON 字符串解析为特定的对象原型(pr

c# - 如何将 C# 匿名类型序列化为 JSON 字符串?

java - HttpServletRequest 获取 JSON POST 数据

ios - 如何使用 NSJSONSerialization

python - 如何在 Python 中检查字符串是否是有效的 JSON?

javascript - JSON 省略了 Infinity 和 NaN; ECMAScript 中

python - 如何将网页中的 JSON 转换为 Python 脚本

python - 存储 Python 字典