【发布时间】:2016-01-26 02:52:49
【问题描述】:
我有一个从 mysql 表中获取数据的脚本。表中的一列包含西班牙字符,如 á、é 等,在执行主查询之前,它被设置为 utf8 输出。
执行查询后,包含上述特殊字符的数据很好,我可以打印出来而没有看到任何不同。但是,我的问题是当我创建一个 json 文件作为输出并保存文件时,生成的数据被编码为 unicode 而不是西班牙文本。我也尝试过解码 mysql 的输出并在保存 json 文件时进行编码,但我仍然在 unicode 中看到那些特殊字符。
我知道在使用特殊字符之前必须解码->unicode,最后如果我想保存数据,就必须对其进行编码。但是,这行不通。您可以看到我的 Python 脚本的简短版本。
import json
import collections
#Database connection
...
#getting the cursor
cursor = db.cursor()
cursor.execute(' SET NAMES utf8' )
cursor.execute('SELECT * FROM eqs ORDER BY localdate DESC, localtime DESC')
....
master_object= collections.OrderedDict()
for row in rows:
#adding data within the master_object
j=json.dumps(master_object) # <- Here, I tried enconding the data (master_object,enconding='utf-8') and with in the for loop i decode the string
fo=open('output.json','w')
fo.write(j)
fo.close()
【问题讨论】: