【问题标题】:TypeError: string indices must be integers // working with JSON as dict in pythonTypeError: string indices must be integers // 使用 JSON 作为 python 中的 dict
【发布时间】:2017-10-31 07:53:35
【问题描述】:

好的,过去 2 天我一直在努力解决这个问题,但没有真正的进展。我是 python 和一般编码的初学者,但这是我自己无法解决的第一个问题。

所以我有这个带有 JSON 格式的长文件,其中包含来自 youtubeapi 的大约 7000 个条目。 现在我想要一个简短的脚本来打印某个字典键(称为“键”)的某些信息(“videoId”):

我的脚本

import json

f = open ('path file.txt', 'r')
s = f.read()

trailers = json.loads(s)
print(trailers['key']['Items']['id']['videoId'])
# print(trailers['key']['videoId'] gives same response

错误:

print(trailers['key']['Items']['id']['videoId'])
TypeError: string indices must be integers

当我想打印字典键的所有信息时,它确实有效: 此脚本有效

import json

f = open ('path file.txt', 'r')
s = f.read()

trailers = json.loads(s)
print(trailers['key'])

还有 print(type(trailers)) 会导致 class 'dict',正如它应该的那样。

我的 JSON 文件格式如下,来自 youtube API,youtube#searchListResponse。

{
 "kind": "youtube#searchListResponse",
 "etag": "",
 "nextPageToken": "",
 "regionCode": "",
 "pageInfo": {
  "totalResults": 1000000,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#searchResult",
   "etag": "",
   "id": {
    "kind": "youtube#video",
    "videoId": ""
   },
   "snippet": {
    "publishedAt": "",
    "channelId": "",
    "title": "",
    "description": "",
    "thumbnails": {
     "default": {
      "url": "",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "",
      "width": 480,
      "height": 360
     }
    },
    "channelTitle": "",
    "liveBroadcastContent": "none"
   }
  }
 ]
}

您还需要提供哪些其他信息才能理解问题?

【问题讨论】:

  • 你能试试print(trailers['key']['items'][0]['id']['videoId']),因为items是一个字典列表
  • 1. “项目”应该是小写的,不是吗? 2. 注意“items”如何包含对象列表,而不是单个对象。
  • 顺便说一句,你应该使用with open('path file.txt') as f: trailers = json.load(f)
  • @juanpa.arrivillaga 那是一样的东西,但写得更“pythony”对吗?也是故意用 json.load 代替 json.loads 吗?
  • @Carcigenicate 是的,应该是,改变了。我想这是真的,但我该怎么做呢?

标签: python json dictionary youtube typeerror


【解决方案1】:

以下代码为我提供了所提供示例数据中的所有 videoId(实际上根本没有 id):

import json

with open('sampledata', 'r') as datafile:
    data = json.loads(datafile.read())
print([item['id']['videoId'] for item in data['items']])

也许你可以用更多的数据试试这个。

希望这会有所帮助。

【讨论】:

  • 感谢您的回答!这确实是要走的路,在这条线消失几天后,我自己想通了。具体来说,问题是我有 1 个文本文件,其中包含所有 7000 个 api 结果的字典。我应该在字典中的每个条目(api 结果)上完成 json.loads。愚蠢的错误,但当我开始编码时非常困惑。
  • 呵呵,是的,有道理。您是否已经将ptpythonpudb 添加到您的python 工具包中?他们可能会帮助您在未来更快地确定这些事情。享受吧!
【解决方案2】:

我并没有真正查看 youtube api,但查看代码和您提供的示例似乎您错过了 [0]。查看 json 的结构,在关键 items 中有一个列表。

import json

f = open ('json1.json', 'r')
s = f.read()

trailers = json.loads(s)
print(trailers['items'][0]['id']['videoId'])

【讨论】:

  • 假设你忘记了 ['key'] 那里,但我仍然得到同样的错误。虽然我认为这无关紧要,但我是从 .txt 文件中导入的。应该不是问题吧?
  • 我故意省略了 ['key'] 因为您提供的示例中没有“key”。是的,您可以使用 .txt 文件。顺便说一句,您可以随时尝试trailers['items']trailers['items'][0]trailers['items'][0]['id'] ... 找出问题所在
【解决方案3】:

我以前根本没有使用过 json。但它基本上是以带有更多字典、列表等的字典形式导入的。在适用的情况下。至少在我的理解中。

所以当你执行type(trailers) 时,你会得到输入 dict。然后你用trailers['key']做dict。如果你这样做,它也应该是一个字典,如果一切正常的话。处理每个 dict 中的项目最终应该会发现你的错误。

Pythons 错误表示您正在尝试查找仅接受整数的字符串的索引/索引,而您正在尝试使用 dict。所以你需要找出为什么你在使用每个参数时得到一个字符串而不是 dict。

编辑以添加示例。如果您的 dict 在键“item”上包含一个字符串,那么您会得到一个字符串作为回报,而不是一个新的 dict,您可以进一步从中获取一个 dict。例如,json 中的item 似乎是一个列表,其中包含字典。不是字典本身。

【讨论】:

  • 我想我发现你的答案有问题,如果我这样做 type(trailers['key']) 我得到类型 str。甚至没有一个列表,所以我不能索引它,它只会得到一个字符。
  • 那么,当您打印整个trailer 时,它会显示“key”键下的内容吗?您能否编辑问题以显示为print(trailer) 打印的所有内容?
猜你喜欢
  • 2013-09-26
  • 1970-01-01
  • 1970-01-01
  • 2020-10-18
  • 2020-01-20
  • 1970-01-01
  • 2012-03-03
  • 2020-09-04
  • 1970-01-01
相关资源
最近更新 更多