繁体   English   中英

TypeError:字符串索引必须是JSON的整数

[英]TypeError: string indices must be integers for JSON

我正在用Python编写程序以提示输入URL,使用urllib从该URL读取JSON数据,然后解析并从JSON数据中提取注释计数,计算文件中数字的总和,然后在下面输入总和。 这是我的代码:

import urllib
import json

total = 0
url = open("comments_42.json")
print 'Retrieving', url
#uh = urllib.urlopen(url)
data = url.read()
print 'Retrieved',len(data),'characters'
#print data

info = json.loads(data)
print info
print 'User count:', len(info)


for item in info:
    print item['count']
    total = total + item['count']

print total

我收到的错误是:

TypeError: string indices must be integers" for "print item['count']

为什么它们必须是整数? 我的Coursera老师也做了类似的事情。 有什么建议吗?

JSON文件具有以下结构:

{
  comments: [
    {
      name: "Matthias"
      count: 97
    },
    {
      name: "Geomer"
      count: 97
    }
    ...
  ]
}

错误"TypeError: string indices must be integers" for "print item['count']"表示该item为字符串; 在这种情况下,这是一个字典键。

我没有看到您的JSON,但是如果您的“ comments_42.json”是此数据集 ,请尝试以下代码:

total = 0
for item in info["comments"]:
    print item['count']
    total += item["count"]

我在这里找到了它(也许有人解决了这个难题或它是什么,然后上传了解决方案)

它告诉您该项是一个字符串,这意味着您的JSON结构与您在课程中使用的结构不同。 例如

info = ['the', 'items', 'inside', 'this', 'list', 'are', 'strings']

for item in info:
    # Items here are strings (the, information, etc)
    print(items) # this will print each word in the list




info = {'sentence': 'the', 'items', 'inside', 'this', 'list', 'are', 'strings'}

for items in info:
    # This is a dictionary, which can be addressed by the key name
    print(items['sentence'])  # this is what you're expecting, because 'sentence' is a dictionary key.

如果您将JSON响应添加到原始问题,我们可以帮助您了解如何访问所需的项目。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM