Python处理JSON时的值报错及编码报错的两则解决实录
2016-06-26 18:01
656 查看
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的lib\site-packages文件夹下新建一个sitecustomize.py,内容如下:
# encoding=utf8import sys reload(sys) sys.setdefaultencoding('utf8')
这样的话,系统在Python启动的时候,自行调用该文件,设置系统的默认编码。
您可能感兴趣的文章:
- Python运行报错UnicodeDecodeError的解决方法
- Python安装Imaging报错:The _imaging C module is not installed问题解决方法
- Python首次安装后运行报错(0xc000007b)的解决方法
- 解决Python requests 报错方法集锦
- 解决Python中字符串和数字拼接报错的方法
- 完美解决python遍历删除字典里值为空的元素报错问题
- 解决python3 urllib中urlopen报错的问题
- Python 使用os.remove删除文件夹时报错的解决方法
- python中异常报错处理方法汇总
- 新手常见6种的python报错及解决方法
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法