无法将mysql中的特殊字符存储到json文件Python中

2024-04-19 21:46:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从mysql表获取数据的脚本。表中的一列包含西班牙语字符,如á、é等,在执行主查询之前,设置utf8输出。在

在执行查询之后,包含上述特殊字符的数据是正常的,我可以打印出来,而不会看到任何不同。但是,我的问题是,当我创建一个json文件作为输出并保存文件时,结果数据被编码为unicode而不是西班牙语文本。我也尝试过在保存json文件时对mysql的输出进行解码和编码,但我仍然看到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()

Tags: 文件the数据master脚本json编码object
1条回答
网友
1楼 · 发布于 2024-04-19 21:46:25

您似乎正在使用json编码的字符串创建一个ASCII编码的json文件,这是存储json文件的典型用例。在

我想你需要一个UTF-8编码的json文件。为此,请在json编码步骤中设置ensure_ascii=False,以便utf8编码的字符串直接传递到文件中。在

像这样的东西可能对你有用。在

import json
master_objects = {
    "tomorrow" : "ma\xc3\xb1ana" # UTF-8 encoding, just like what comes from db
}

print master_objects["tomorrow"] # Should print man~ana, only prettier

with open("output.json", "wt") as output_file:
    json.dump(master_objects, output_file, ensure_ascii=False)

相关问题 更多 >