Python:json.dumps无法处理utf-8? [英] python: json.dumps can't handle utf-8?

查看:412
本文介绍了Python:json.dumps无法处理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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆