Heim >Backend-Entwicklung >Python-Tutorial >python处理json数据中的中文

python处理json数据中的中文

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

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参数

 

 

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:Python 异常处理实例详解Nächster Artikel:python显示天气预报