Python:json.dumps无法处理utf-8? [英] python: json.dumps can't handle utf-8?
问题描述
下面是测试程序,包括一个汉字:
Below is the test program, including a Chinese character:
# -*- coding: utf-8 -*-
import json
j = {"d":"中", "e":"a"}
json = json.dumps(j, encoding="utf-8")
print json
下面是结果,请看json.dumps将utf-8转换为原始数字!
Below is the result, look the json.dumps convert the utf-8 to the original numbers!
{"e": "a", "d": "\u4e2d"}
为什么这个坏了?还是我错了?
Why this is broken? Or anything I am wrong?
推荐答案
您应该阅读 json.org .完整的JSON规范在右侧的白框中.
You should read json.org. The complete JSON specification is in the white box on the right.
生成的JSON没有错.允许生成器生成UTF-8字符串或纯ASCII字符串,这些字符使用\uXXXX
表示符转义.在您的情况下,Python json
模块决定转义,而中
具有转义符号 \u4e2d
.
There is nothing wrong with the generated JSON. Generators are allowed to genereate either UTF-8 strings or plain ASCII strings, where characters are escaped with the \uXXXX
notation. In your case, the Python json
module decided for escaping, and 中
has the escaped notation \u4e2d
.
顺便说一句:任何符合条件的JSON解释器都会再次正确地取消转义此序列,并退还给您实际的字符.
By the way: Any conforming JSON interpreter will correctly unescape this sequence again and give you back the actual character.
这篇关于Python:json.dumps无法处理utf-8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!