Home >Backend Development >Python Tutorial >python处理json数据中的中文

python处理json数据中的中文

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-16 08:44:591129browse

python中自带了处理python的模块,使用时候直接import json即可。 使用loads方法即可将json字符串转换成python对象,对应关系如下:
JSON     Python
object   dict
array    list
string   unicode
number   (int) int, long
number   (real) float
true     True
false    False
null     None

但在使用json模块的时候需要注意的是对中文的处理,loads方法如果传入的字符串的编码不是UTF-8的话,需要用encoding指定字符编码

复制代码 代码如下:

import json
import base64
f = open("./result_diff.txt")
for l in f:
try:
    fp = l[l.find("?fp")+1 :]
    Http = fp.find("HTTP/")
    fp = fp[3:Http-1]
fp = fp.decode("gbk").encode("utf-8")
str1 = json.loads(fp, encoding="utf-8")
print str1
except Exception, e:
print str(e)

当fp中含有中文并且是gbk编码的时候,当我们把当前行的编码改成utf8后在使用json进行解码的时候需要指定编码。
或者这样

复制代码 代码如下:

fp = fp.decode("gbk")
直接转成gbk编码,就可以不用指定json的编码类型,就是不用使用encoding参数

 

 

Statement:
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