python JSON 中文 unicode 的性能问题

python2.x 版的字符编码一直是大家的诟病,字典转换成json时中文字符串变成 unicode。

Python json unicode

unicode转换

转换会转成类似这样的 \u65b0\u8f66 字符。

要想显示中文则需加个参数:

1
json.dumps(some_dict, ensure_ascii=False)

设置 ensure_ascii=False 可以节省大量内存,但 json 在设置 ensure_ascii=False 后性能急剧下降。ujson 还好。

1
Converts arbitrary object recursivly into JSON. Use ensure_ascii=false to output UTF-8. Pass in double_precision to alter the maximum digit precision of doubles. Set encode_html_chars=True to encode < > & as unicode escape sequences.

python 编码类型

在python 2或者3 ,字符串编码只有两类 :

  • (1)通用的Unicode编码;
  • (2)将Unicode转化为某种类型的编码,如UTF-8,GBK;

encode()和decode()的区别

encode() 的作用是将Unicode编码的字符串转换为其他编码格式。

例如: st1.encode("utf-8") 这句的作用是将Unicode编码的st1编码为utf-8编码的字符串

decode() 的作用是把其他编码格式的字符串转换成Unicode编码的字符串。

例如: st2.decode("utf-8") 这句的作用是将utf-8编码的字符串st2解码为Unicode编码的字符串

编码之间互转

除Unicode编码的字符串以外,任何一种编码的字符串要想转换为其他编码格式,必须先解码后编码

非Unicode编码--> Unicode编码-->非Unicode编码

例如,utf-8编码的字符串st想要转换为gbk编码的字符串,必须经过以下步骤:

1
2
st=st.decode("utf-8") #解码为Unicode编码
st=st.encode("gbk") #从Unicode编码编码为gbk编码

本文网址: https://pylist.com/topic/52.html 转摘请注明来源

Suggested Topics

python中文链接安全转码

当一个链接里包含中文时,有些浏览器并不能正确解析,这就需要首先对中文作安全转码,这里介绍用 python中文链接安全转码,...

Leave a Comment