1

Right now I am just trying to print out the JSON through python. Eventually I will be using information from the requested JSON but I am stuck at just getting it into something I can work with.

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)

This is where I started. I get the error

the JSON object must be str, not 'bytes'

on the "videos = json.load(response)" line.

Searching around and ended up trying out

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

With that I get this error

Traceback (most recent call last): File "C:\Users\Sean\Documents\NeebsBot\NeebsBot\NeebsBot\NeebsBot.py", line 13, in videos = json.load(response.decode()) AttributeError: 'HTTPResponse' object has no attribute 'decode' Press any key to continue . . .

Searched again and tried this.

response = urllib.request.urlopen(url)

content = response.read()

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

print(videos)

And I get this when I run

'charmap' codec can't encode character '\xa9' in position 1573: character maps to

All the solutions I have found online always brings me back to these errors.

DarthIrule
  • 15
  • 3
  • Show the beginning of content, but you could also try to decode it as ISO-8859-1 or Latin1 with `videos = json.loads(content.decode('latin1'))` – Serge Ballesta Oct 05 '15 at 05:51

1 Answers1

1

You are most likely receiving gzipped content, as a sample request to the Youtube API returned the following headers:

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

You have two choices here, you can add the snippet from this question to decompress the content, or use the popular requests library which takes care of all this for you.

In requests, your code would be:

import requests

r = requests.get(your_url_goes_here)
results = r.json()
print(results) 
Community
  • 1
  • 1
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • I get the same error "'charmap' codec can't encode character '\xa9' in position 725: character maps to " – DarthIrule Oct 05 '15 at 06:04
  • Ok I got this to work using a different IDE. I have been using Visual Studio 2015. I tried your solution out in pycharm and it works. Gotta love stuff like that, right? – DarthIrule Oct 06 '15 at 04:52