从Google GitHub rep加载JSON数据

2024-04-24 18:49:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试用Python加载以下JSON文件(来自Google Github repo),如下所示:

import json
import requests

url = "https://raw.githubusercontent.com/google/vsaq/master/questionnaires/webapp.json"
r = requests.get(url)
data = r.text.splitlines(True)
#remove first n lines which is not JSON (commented license)
data = ''.join(data[14:])

当我使用json.loads(data)时,会出现以下错误:

JSONDecodeError: Expecting ',' delimiter: line 725 column 543 (char 54975)

由于这已经被GitHub repo所有者(Google)保存为json文件,我想知道我在这里做错了什么。你知道吗


Tags: 文件httpsimportgithubcomjsonurldata
1条回答
网友
1楼 · 发布于 2024-04-24 18:49:33

我发现从API调用获得的文本就像一个简单的文本,而不是一个有效的JSON(我在https://jsonformatter.curiousconcept.com/处进行了检查)。你知道吗

下面是我用来从响应中过滤有效JSON部分的代码。你知道吗

I have used re module to extract the JSON part.

import json
import requests
import re

url = "https://raw.githubusercontent.com/google/vsaq/master/questionnaires/webapp.json"
r = requests.get(url)
text = r.text.strip()

m = re.search(r'\{(.|\s)*\}',  text) # It is for finding a valid JSON part from obtained text
s = m.group(0).replace('false', 'False') # Python has 'False/True' not 'false/true' (Replacement)
d = eval(s)

print(d) # {...}
print(type(d)) # <class 'dict'>
参考资料»

相关问题 更多 >