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

WBOY
Release: 2016-07-06 13:29:46
Original
1395 people have browsed it

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)
Copy after login

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

json_data = json_data.replace('\r', '\\r').replace('\n', '\\n')
Copy after login

(2)使用关键字strict:

json.loads(json_data, strict=False)
Copy after login

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')
Copy after login

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

# encoding=utf8 
import sys 

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

Copy after login

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!