Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python json错误:字符串索引必须是整数_Python_Json - Fatal编程技术网

python json错误:字符串索引必须是整数

python json错误:字符串索引必须是整数,python,json,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), 'c

您好,当我学习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"]
url包含如下内容

{
  "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
    },}

您应该使用
print item[“comments”][0][“count”]
print item[“comments”][1][“count”]
等等。您应该使用片的索引,然后从dicts中搜索
“count”

您还可以使用以下内容:

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

您的
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"]

您迭代解析字典中的每个值,即
info
中的
item
s是

  • “此文件包含用于测试的样本数据”
  • [{“姓名”:“罗米娜”,“伯爵”:97},{“姓名”:“劳里”,“伯爵”:97},{“姓名”:“巴利”,“伯爵”:90},{“姓名”:“西约娜”,“伯爵”:90},{“姓名”:“泰莎”,“伯爵”:88},{“姓名”:“阿梅利亚”,“伯爵”:87},
因此,在第一次迭代中,您尝试从实际字符串中获取
[“comments”][“count”]

如果要打印每个comments元素的计数,则应:

对于信息[“注释”]中的项目:
打印项目[“计数”]


最好的调试方法是,只需使用解释器(IPython或Jupyter笔记本对此非常有用),将页面分配给变量,甚至创建一个具有相同结构的模拟页面,然后解析它,以验证代码的正确性。这里的问题是代码的解析方式。

非常感谢!我以前不明白。您还可以使用不同的方式提取这些类型的值。如果你愿意,我可以编辑我的答案。