【Error】 json file 不能读取的解决办法 TypeError: Input string must be text, not bytes

最开始是用

with open(path) as f:
	data = json.loads(f)

然后报错TypeError: Input string must be text, not bytes

尝试1,加上解码:

with open(path, encoding='utf-8') as f:
	data = json.loads(f)

仍报错TypeError: Input string must be text, not bytes

尝试2,读取每行:

with open(path, encoding='utf-8') as f:
	data = [json.loads(line) for line in f]

报错JSONDecodeError: Expecting property name enclosed in double quotes or '}'

这时候,我们知道,肯定是json file里面有些“非法”字符需要删除。

最终尝试,使用nested replace去除“非法”字符:

# nested replace() 
with open(gentle_file, encoding='utf-8') as f:
    tmp = f.read().replace('\t','').replace('\n','').replace(',}','}').replace(',]',']')
    data = json.loads(tmp)

成功!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值