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

2024-10-02 22:33:59 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,当我学习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
    },}

Tags: nameimportinfojsonurlfordatalen
3条回答

您遍历已解析字典中的每个值,即item中的info

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

因此,在第一次迭代中,您尝试从实际字符串中获取["comments"]["count"]。你知道吗

如果要打印每个注释元素的计数,则应: for item in info["comments"]: print item["count"]

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

您应该使用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"]

相关问题 更多 >