簡體   English   中英

無法將mysql中的特殊字符存儲到json文件中-Python

[英]unable to store special characters from mysql into a json file - 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()

您似乎正在用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM