我想编写一个程序,向我提供YouTube频道有多少订阅者的实时供稿。为此,我使用了Google的api,该api在json文件中提供了信息:
{
"kind": "youtube#channelListResponse",
"etag": "\"XI7nbFXulYBIpL0ayR_gDh3eu1k/wTcrqM2kHwjf7GxOEpSBk_lofRA\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#channel",
"etag": "\"XI7nbFXulYBIpL0ayR_gDh3eu1k/HhHZCWV2vASrbydwK9ItUgUm0X8\"",
"id": "UC-lHJZR3Gqxm24_Vd_AJ5Yw",
"statistics": {
"viewCount": "19893639729",
"commentCount": "0",
"subscriberCount": "79695778",
"hiddenSubscriberCount": false,
"videoCount": "3707"
}
}
]
}
代码如下:
import json
json_str = '''{
{
"kind": "youtube#channelListResponse",
"etag": "\"XI7nbFXulYBIpL0ayR_gDh3eu1k/wTcrqM2kHwjf7GxOEpSBk_lofRA\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#channel",
"etag": "\"XI7nbFXulYBIpL0ayR_gDh3eu1k/HhHZCWV2vASrbydwK9ItUgUm0X8\"",
"id": "UC-lHJZR3Gqxm24_Vd_AJ5Yw",
"statistics": {
"viewCount": "19893639729",
"commentCount": "0",
"subscriberCount": "79695778",
"hiddenSubscriberCount": false,
"videoCount": "3707"
}
}
]
}
'''
data = json.loads(json_str)
print(data)
但是当我尝试使用json.loads()将其转换为python字典时,出现以下错误:
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 2 (char 3)
也:
print(ascii(json_str))
'{\n {\n "kind": "youtube#channelListResponse",\n "etag": ""XI7nbFXulYBIpL0ayR_gDh3eu1k/wTcrqM2kHwjf7GxOEpSBk_lofRA"",\n "pageInfo": {\n "totalResults": 1,\n "resultsPerPage": 5\n },\n "items": [\n {\n "kind": "youtube#channel",\n "etag": ""XI7nbFXulYBIpL0ayR_gDh3eu1k/HhHZCWV2vASrbydwK9ItUgUm0X8"",\n "id": "UC-lHJZR3Gqxm24_Vd_AJ5Yw",\n "statistics": {\n "viewCount": "19893639729",\n "commentCount": "0",\n "subscriberCount": "79695778",\n "hiddenSubscriberCount": false,\n "videoCount": "3707"\n }\n }\n ]\n}\n'
是什么原因引起的问题?
答案 0 :(得分:2)
使用以下代码,我可以打开您的JSON并进行打印。将您的JSON保存到temp.json,然后尝试以下操作:
import json
with open("temp.json", "r") as infile:
data = json.loads(infile.read())
print(data)