Search code examples
pythonjsonterminalyoutube-apifetch

Python Fetch JSON Output is inline in the Terminal


I am fetching the YouTube API v3 and I am getting a inline output with no formatting. I try many things but it doesn't change. I really want this formatted Terminal input which JSON is known for. A little example to make it clear.

Instead of that:

{'kind': 'youtube#playlistItemListResponse', 'etag': '"RmznBCICv9YtgWaaa_nWDIH1_GM/LWynQ43ZRLDxlXRu2FEsftoi3DU"', 'nextPageToken': 'CAUQAA', 'pageInfo': {'totalResults': 3265, 'resultsPerPage': 5}, 'items': [{'kind': 'youtube#playlistItem', 'etag': '"RmznBCICv9YtgWaaa_nWDIH1_GM/RLsCuhCsMwlWfN_9qY8Zx1Movtg"', 'id': 'VVVCdy1EejZ3SFJreGlYS0NMb1dxRHpBLkNITXJrSUhjS3Nj', 'snippet': 

I want that:

 {
 "kind": "youtube#playlistItemListResponse",
 "etag": "\"RmznBCICv9YtgWaaa_nWDIH1_GM/nuvTmMmYuXL-OSks1LuYTjHgwQI\"",
 "nextPageToken": "CAUQAA",
 "pageInfo": {
  "totalResults": 3265,
  "resultsPerPage": 5
 },
 "items": [

Code:

def getVideoFromChannel():
channelName = ""
getPlaylistVideo = urlReq.urlopen("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=5&playlistId=UUBw-Dz6wHRkxiXKCLoWqDzA&key="+api_key)
data = json.loads(getPlaylistVideo.read().decode(getPlaylistVideo.info().get_param('charset') or 'utf-8'))
print(data)

Solution

  • Try the following:

    print(json.dumps(data, indent=4, sort_keys=True))
    

    More info can be found here: How to prettyprint a JSON file?