【发布时间】: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