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.
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'}}]}
I actually turned the dict into a string, but ill try this.
Ok, it works fine, thanks!
Also please consider generating a new api key if possible. Since current one got exposed to internet.
I will, thanks for telling me I didn't see that.