【问题标题】:string indices must be integers json file字符串索引必须是整数 json 文件
【发布时间】:2022-01-14 06:03:56
【问题描述】:

我试图使用 API 从 youtube 获取数据,希望我做到了,但是在尝试解析文件时出现错误,字符串索引必须是整数。

以下是我面临的错误......

TypeError                                 
Traceback (most recent call last)
<ipython-input-48-213e690c5b60> in <module>----> 1 response['items'][0]['id']['videoId']['snippet']['title']

TypeError: string indices must be integers

实际上,我正试图从频道中获取第一个视频,所以我输入了response['items'][0],我很容易就得到了……但是当我试图解析那个视频的Video_IDTitle 时,我得到了这个错误。

但是,当我单独执行它们时,我得到了输出。

单独执行时的输出:

response['items'][0]['id']['videoId']
'gzJGqML4j5k'

response['items'][0]['snippet']['title']
'Roles And Responsibilities Of An AI Engineer'

一起执行时的输出:

response['items'][0]['id']['videoId']['snippet']['title']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-50-213e690c5b60> in <module>
----> 1 response['items'][0]['id']['videoId']['snippet']['title']

TypeError: string indices must be integers

谁能帮助我并告诉我如何在一个命令中获得此输出。

【问题讨论】:

  • 你能分享示例json吗?
  • 是什么让你觉得你可以做到response['items'][0]['id']['videoId']['snippet']['title']。你看到response['items'][0]['id'] 是一个字符串'gzJGqML4j5k',而你基本上是'gzJGqML4j5k'['snippet']['title']。此外,尚不清楚预期的输出。
  • 是的,当然...我正在分享第一个视频 Json 脚本 {'kind': 'youtube#searchResult', 'etag': 'zEAAkzvpAKSGeDxW0Y4McGc-gtA', 'id': {'kind' :'youtube#video','videoId':'gzJGqML4j5k'},'sn-p':{'publishedAt':'2021-12-07T13:30:14Z','channelId':'UCNU_lfiiWBdtULKOw6X0Dig','title' :“人工智能工程师的角色和责任”,
  • 将 2 个语句合并为一个命令的目的是什么?你想从 json 中得到什么样的输出?
  • 如果您只需要在一行中打印它们,请使用print(response['items'][0]['id']['videoId'], response['items'][0]['snippet']['title'])。无法在一个命令中从 json 中获取两个值。

标签: python json api data-science exploratory-data-analysis


【解决方案1】:

当您进入 cmets 时 - 您无法一步从 JSON/dictionary 获取两个值。

您必须分别获取每个值并在一个 print() 中使用这两个值

更具可读性:

val1 = response['items'][0]['id']['videoId']
val2 = response['items'][0]['snippet']['title']

print(val1, val2)

相同但在一行中:

print(response['items'][0]['id']['videoId'], response['items'][0]['snippet']['title'])

或仍然可读的短版本:

item = response['items'][0]

print(item['id']['videoId'], item['snippet']['title'])

它适用于for-loop

for item in response['items']:
    print(item['id']['videoId'], item['snippet']['title'])

【讨论】:

  • 感谢您的详细解释...
  • @KUNALKALKOTWAR 如果这解决了您的问题,那么您可以将我的答案标记为已接受,几分钟后您可以投票(如果您有足够的reputation 点数)
  • 标记为已接受......没有足够的声誉来支持......顺便说一句,感谢您的详细解释......
猜你喜欢
  • 2020-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-06
  • 2021-08-28
相关资源
最近更新 更多