【问题标题】:Having trouble converting JSON from youtube APIv3 to something I can work with in python无法将 youtube APIv3 中的 JSON 转换为我可以在 python 中使用的东西
【发布时间】:2016-01-01 17:10:56
【问题描述】:

现在我只是想通过 python 打印出 JSON。最终,我将使用来自请求的 JSON 的信息,但我只能将其转化为我可以使用的东西。

import urllib
import urllib.request
import dateutil
import json

API_KEY = open("/Users/Sean/Documents/Yer.txt", "r")
API_KEY = API_KEY.read()

url = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=UUiufyZv8iRPTafTw0D4CvnQ&key='+API_KEY

response = urllib.request.urlopen(url)

videos = json.load(response)

print(videos)

这就是我开始的地方。我收到错误

JSON 对象必须是 str,而不是 'bytes'

在“videos = json.load(response)”行上。

四处搜索并最终尝试

videos = json.load(response.decode())

我得到这个错误

Traceback(最近一次调用最后一次): 文件“C:\Users\Sean\Documents\NeebsBot\NeebsBot\NeebsBot\NeebsBot.py”,第 13 行,在 视频 = json.load(response.decode()) AttributeError:“HTTPResponse”对象没有“解码”属性 按任意键继续 。 . .

再次搜索并尝试了这个。

response = urllib.request.urlopen(url)

content = response.read()

videos = json.loads(content.decode('utf8'))

print(videos)

当我运行时我得到了这个

'charmap' 编解码器无法对位置 1573 中的字符 '\xa9' 进行编码:字符映射到

我在网上找到的所有解决方案总是让我想起这些错误。

【问题讨论】:

  • 显示内容的开头,但您也可以尝试使用videos = json.loads(content.decode('latin1'))将其解码为 ISO-8859-1 或 Latin1

标签: python json youtube-data-api


【解决方案1】:

您很可能会收到 gzip 压缩的内容,因为对 Youtube API 的示例请求返回了以下标头:

cache-control:  private, max-age=0, must-revalidate, no-transform
content-encoding:  gzip
content-length:  1706
content-type:  application/json; charset=UTF-8

你有两个选择,你可以add the snippet from this question解压内容,或者使用流行的requests library,它会为你处理这一切。

在请求中,您的代码将是:

import requests

r = requests.get(your_url_goes_here)
results = r.json()
print(results) 

【讨论】:

  • 我得到同样的错误“'charmap'编解码器不能在位置725编码字符'\xa9':字符映射到
  • 好的,我让它使用不同的 IDE 工作。我一直在使用 Visual Studio 2015。我在 pycharm 中尝试了你的解决方案,它可以工作。一定会喜欢这样的东西,对吧?
猜你喜欢
  • 1970-01-01
  • 2022-01-21
  • 2023-03-08
  • 2020-10-03
  • 2021-03-30
  • 1970-01-01
  • 2015-03-31
  • 2019-12-20
  • 1970-01-01
相关资源
最近更新 更多