可以使用以下例子中的代码,使用 Python 的 requests 库在 API 中获取 JSON 字符串,并确保正确解析该字符串。
import requests
import json
url = 'https://example.com/api/'
response = requests.get(url)
json_str = response.text
data = json.loads(json_str)
print(data)
如果 API 返回的 JSON 中包含无效字符,可能会导致解析失败。在这种情况下,可以尝试在解析之前清理字符串,以避免此问题。您可以使用 replace
方法删除无效字符,如下所示。
json_str = json_str.replace('\r\n', '') # 删除回车和换行符
json_str = json_str.replace('\n', '')
json_str = json_str.replace('\r', '')
data = json.loads(json_str)
print(data)
如果上述解决方法不能解决您的问题,请检查 API 返回的 JSON 格式是否正确,并确保正确处理任何错误消息。