json.decoder.JSONDecodeError:Unexpected UTF-8 BOM(decode using utf-8-sig)

json.decoder.JSONDecodeError:Unexpected UTF-8 BOM(decode using utf-8-sig)

问题描述:

问题是这样的,
res=requests.post(url,headers=headers,data=data)
print(res.json())
会出现标题中的错误,怎么解决?感谢大佬们

返回的内容有bom头,要获取返回的内容,判断有BOM头去掉后再用json.loads加载,不能直接.json获取

img


有帮助麻烦点个采纳【本回答右上角】,谢谢~~

import requests
import json
text=requests.post(url,headers=headers,data=data).text
print(text)#有BOM头
if text.startswith(u'\ufeff'):#含BOM头要先去掉BOM头
    text = text.encode('utf8')[3:].decode('utf8')

o=json.loads(text)
print(o)

去掉UTF-8的BOM头,代码如下:

res=requests.post(url,headers=headers,data=data)
text=res
if text.startswith(u'\ufeff'):
  text = text.encode('utf8')[3:].decode('utf8')
  res = text
print(res.json())