【发布时间】: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_ID 和Title 时,我得到了这个错误。
但是,当我单独执行它们时,我得到了输出。
单独执行时的输出:
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