python json错误:string indices must be integers

标签 python json

您好,当我学习 python 时,我被下面的问题阻止了,我在网站上尝试了一些解决方案,但到目前为止没有一个有效。当我编译时,它返回我:字符串索引必须是整数。 你能帮我吗?谢谢。

import json
import urllib

url = raw_input('Enter location: ')
uh = urllib.urlopen(url)
data = uh.read()

print 'Retrieving', url
print 'Retrieved', len(data), 'characters'
info = json.loads(data)
#print 'User count:', len(info)
s = 0

for item in info:
    print item["comments"]["count"]

网址包含类似这样的内容

{
  "note":"This file contains the sample data for testing",
  "comments":[
    {
      "name":"Romina",
      "count":97
    },
    {
      "name":"Laurie",
      "count":97
    },
    {
      "name":"Bayli",
      "count":90
    },
    {
      "name":"Siyona",
      "count":90
    },
    {
      "name":"Taisha",
      "count":88
    },
    {
      "name":"Ameelia",
      "count":87
    },}

最佳答案

您的 for 循环与数据结构不匹配。

试试这个:

for item in info["comments"]:
    print item["count"]

如果您想查看名称与计数的关联,请尝试:

for item in info["comments"]:
    print item["name"], item["count"]

如果您想查看名称、计数及其在该列表中的位置,请尝试:

for index, item in enumerate(info["comments"]):
    print index, item["name"], item["count"]

关于python json错误:string indices must be integers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41470540/

相关文章:

python - 使用区域设置打印以色列货币

python - opencv_creatsamples 错误 : free() :corrupted unsorted chunks:

Python - 如何生成大小大于列表元素数量的排列

python - Pygame 碰撞仅作用于一个对象

javascript - 语法错误: "JSON.parse: unexpected non-whitespace ..." when returning JSON from PHP

python - 有没有一种方法可以在 python 中连接两个对象,使得其中一个对象中的所有值都为另一个对象中的每个值重复

json - Sinatra Controller 参数方法在 JSON 发布请求中为空

javascript - JSON.parse 仅给出最后一个元素作为输出

javascript - 如何防止直接访问我的 JSON 服务?

javascript - Jquery 匹配 JSON 数组中的元素