Warm tip: This article is reproduced from serverfault.com, please click

How do I fix json from the youtube v3 api with python?

发布于 2020-12-03 08:39:31

I am getting youtube data from youtube channels with the youtube v3 api, and I am trying to make the json that it outputs valid. I have replaced all of the single quotes with double quotes, but my only problem is that the json has an item without quotes at all. Here is my python:

from googleapiclient.discovery import build
import json

api_key = "XXXXXXXXXX"

youtube = build('youtube', 'v3', developerKey=api_key)

request = youtube.channels().list(
        part='statistics',
        id="UCZuwBN1DWfgObYprETYk0eg"
    )

response = request.execute()

responsestring = str(response)

replaced = responsestring.replace("'", '"')


print(replaced)

yes = json.loads(replaced)

#responsejson = json.loads(responsestring)
#^this fails because of the invalid json

and here is the outputted json:

{"kind": "youtube#channelListResponse", "etag": "QHkx_kkeJgXRDHWbuMXUaYyQ3EQ", "pageInfo": {"totalResults": 1, "resultsPerPage": 5}, "items": [{"kind": "youtube#channel", "etag": "WXRPwYh-SXn_vwy93t3wnzu99gM", "id": "UCZuwBN1DWfgObYprETYk0eg", "statistics": {"viewCount": "3512315", "subscriberCount": "58600", "hiddenSubscriberCount": False, "videoCount": "151"}}]}

is there a way to make it so that False or True have double quotes on it? (Or just anything without double quotes have double quotes on it). Thanks in advance if you help.

Questioner
HoneyPoop
Viewed
0
venky__ 2020-12-03 16:50:11

First the output is not JSON; It is a dictionary. You can check by doing type(response). Second Dictionary should work fine in most cases. If you still want to convert it to JSON you will have to use JSON.dumps. Below is the code

# Convert dict to JSON
response_JSON = json.dumps(response)
# try to load JSON
json_load = json.loads(response_JSON)
json_load

Out:

{'kind': 'youtube#channelListResponse',
 'etag': '85jouxT6VPwZltMItbtqSpICBgE',
 'pageInfo': {'totalResults': 1, 'resultsPerPage': 5},
 'items': [{'kind': 'youtube#channel',
   'etag': 'gkhgrDmYZaof9gPHKNeDSEtRiBY',
   'id': 'UCZuwBN1DWfgObYprETYk0eg',
   'statistics': {'viewCount': '3512365',
    'subscriberCount': '58600',
    'hiddenSubscriberCount': False,
    'videoCount': '151'}}]}