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

问题描述:

我正在使用Python编写程序以提示输入URL,使用urllib从该URL读取JSON数据,然后解析并从JSON数据中提取评论计数,计算总和文件中的数字并输入下面的总和。这里是我的代码:TypeError:字符串索引必须是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 
    } 
    ... 
    ] 
} 
+0

相似是不一样的。它很可能是一本字典,其中的密钥可以是任何(可排列)类型。 – Reti43

+0

看来'item'是一个'string'而不是'dict'。 – AKS

+0

所有的东西都是平等的,不是一个坏主意,看看你的JSON是否确实是有效的JSON。 http://jsonlint.com/说它不是。 –

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

我还没有看到你的JSON,但如果你的“comments_42.json”为this dataset,试试下面的代码:

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

我发现它here(也许有人解决了这个挑战,或者不管它是什么,并上传解决方案)

+0

我刚刚尝试过,并且得到相同的错误。 – abadila123

+0

好吧,所以我尝试了你的代码,它会去“ImportError:no module named requests。” – abadila123

+0

@ abadila123'requests'只需要在线获取数据集。您似乎已将其放在您的计算机上,因此您可以将其删除。检查我更新的答案。顺便说一句。我们可以在一分钟内解决这个问题,如果你在你的问题中发布了json或其中的一部分 – jDo

它告诉你item是一个字符串,这意味着你的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响应原来的问题,我们可以帮助您了解如何获取你想要的物品。