python - 在 python 中推送到 json 时丢失字符串编码

标签 python linux utf-8

我试图在运行 mysql 查询的 Linux 服务器上用 Python 运行一个脚本,该查询会产生一些希伯来语字符串(这里为了简化而将其设为一个),如下所示:

#!/usr/bin/env  python
# -*- coding: utf-8 -*-
import cgi
import cgitb;cgitb.enable()
import sys
import urllib
import base64
from MySQL import sql
print """Content-Type: text/html\n"""
s = sql()
s.run("SET NAMES utf8;")
query = "SELECT page FROM pages"
results = s.run(query)
s.close()
ans = {}
ans['count'] = 0
ans['items'] = []    
for res in results:
    page = result[0].encode('utf-8')
    print "====="+page+"======"
    ans['items'].append({
           'td0':page
    })
print ans
s.close()

这笨拙地打印

"Content-Type: text/html"

====/מפת-זרזיר/גריפאת/1/====
{'count': 0, 'items': [{ 'td0': '/\xd7\x9e\xd7\xa4\xd7\xaa-\xd7\x96\xd7\xa8\xd7\x96\xd7\x99\xd7\xa8/\xd7\x92\xd7\xa8\xd7\x99\xd7\xa4\xd7\x90\xd7\xaa/1/'}]}

为什么哦为什么字典中的页面会丢失编码??? 我不知道为什么会这样。任何帮助将不胜感激。

谢谢

最佳答案

您不应该手动编码数据。请改用 json 模块,并将数据保留为 Unicode:

import json

for res in results:
    page = result[0]
    print "====={}======".format(page.encode('utf8')
    ans['items'].append({
        'td0':page
    })

print json.dumps(ans)

json 模块将为您处理编码。

您打印的是 Python 字典,而不是 JSON 映射,Python 使用字符串文字表示字符串中的字节。此表示使用 \x.. 转义符来表示任何不可打印的字符。由于是直接打印UTF-8数据,数据中包含很多不可打印的字节,但数据还在:

>>> print '/\xd7\x9e\xd7\xa4\xd7\xaa-\xd7\x96\xd7\xa8\xd7\x96\xd7\x99\xd7\xa8/\xd7\x92\xd7\xa8\xd7\x99\xd7\xa4\xd7\x90\xd7\xaa/1/'.decode('utf8')
/מפת-זרזיר/גריפאת/1/

如果我采用您的示例值并使用 json 模块,另一方面会生成有效的 JSON 输出:

>>> ans = {'count': 0, 'items': []}
>>> ans['items'].append('/\xd7\x9e\xd7\xa4\xd7\xaa-\xd7\x96\xd7\xa8\xd7\x96\xd7\x99\xd7\xa8/\xd7\x92\xd7\xa8\xd7\x99\xd7\xa4\xd7\x90\xd7\xaa/1/'.decode('utf8'))
>>> import json
>>> print json.dumps(ans)
{"count": 0, "items": ["/\u05de\u05e4\u05ea-\u05d6\u05e8\u05d6\u05d9\u05e8/\u05d2\u05e8\u05d9\u05e4\u05d0\u05ea/1/"]}

JSON 允许使用 \u.... 转义码,并且该模块使用这些转义码来表示非 ASCII 和不可打印的字符。这是正常的,兼容的 JSON 解码器可以很好地读取它。

关于python - 在 python 中推送到 json 时丢失字符串编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16420386/

相关文章:

Python 2.7 : Adding all elements of multiple arrays together

python - Python 3.4 和阅读这个简单的 XML 站点有什么关系?

python - 如何使用 python 将 utf-8 字符串转换为 big5?

c - linux猫: No such file or directory

Java Unicode 字符转 UTF

ruby - 在ruby中将utf-8转换为unicode

python - 使用 python 3 Base64 解码 CSV 文件中的单列

python - 'method' 对象在 python 中不可使用子脚本

linux - 使用 pgrep 获取 Linux 进程 ID

linux - 根据分隔符将一个文件拆分为多个文件