Sovrn联盟API返回JSON被NULL包裹致解析失败求助
解决Sovrn API响应JSON解析失败的问题
问题核心是API返回的是JSONP格式(而非纯JSON),虽然响应头标记为application/json,但实际文本被NULL(...)包裹,导致json.loads()无法解析。
处理步骤:
提取响应文本中包裹的JSON部分,去掉外层的NULL(和);即可。
代码实现:
import json import requests url = 'URL-goes-here' headers = { "accept": "application/json", "authorization": "VERY-HARD-TO-GUESS" } response = requests.get(url, headers=headers) # 提取JSON核心部分 raw_response = response.text # 找到JSON起始和结束位置,截取有效内容 start_pos = raw_response.find('(') + 1 end_pos = raw_response.rfind(')') json_content = raw_response[start_pos:end_pos] # 解析JSON product_details = json.loads(json_content) print(product_details)
简化写法(适用于格式稳定的情况):
如果确认响应格式固定为NULL({...});,可以直接用字符串替换:
json_content = response.text.replace('NULL(', '').rstrip(');') product_details = json.loads(json_content)
内容的提问来源于stack exchange,提问作者Zsolt Balla
相关产品推荐
相关产品推荐

