加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python处理JSON时的值报错及编码报错的两则解决实录

发布时间:2020-12-16 20:34:32 所属栏目:Python 来源:网络整理
导读:1、ValueError: Invalid control character at: line 1 column 8363 (char 8362) 使用json.loads(json_data)时,出现: ValueError: Invalid control character at: line 1 column 8363 (char 8362) 出现错误的原因是字符串中包含了回车符(r)或者换行符(

1、ValueError: Invalid control character at: line 1 column 8363 (char 8362)
使用json.loads(json_data)时,出现:

ValueError: Invalid control character at: line 1 column 8363 (char 8362)

出现错误的原因是字符串中包含了回车符(r)或者换行符(n)
解决方法:
(1)对这些字符转义:

json_data = json_data.replace('r','r').replace('n','n')

(2)使用关键字strict:

json.loads(json_data,strict=False)

strict默认是True,它将严格控制内部字符串,将其设置为False,便可以允许你n r。


2、UnicodeEncodeError: ascii codec can't encode错误
在windows下写的python脚本,放到linux下运行,直接报:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-11: ordinal not in range(128)

出错原因是Python2.7在安装时,默认的编码是ascii,当程序中出现非ascii编码时,Python的处理常常会报这样的错,不过在Python3中就不会有这样的问题。
解决方法:
(1)临时解决方法:
在代码前加入:
import sys 
reload(sys) 
sys.setdefaultencoding('utf8')

(2)一劳永逸:
在Python的libsite-packages文件夹下新建一个sitecustomize.py,内容如下:

# encoding=utf8 
import sys 

reload(sys) 
sys.setdefaultencoding('utf8')

这样的话,系统在Python启动的时候,自行调用该文件,设置系统的默认编码。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读