【问题标题】:unable to store special characters from mysql into a json file - Python无法将 mysql 中的特殊字符存储到 json 文件中 - Python
【发布时间】:2016-01-26 02:52:49
【问题描述】:

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

执行查询后,包含上述特殊字符的数据很好,我可以打印出来而没有看到任何不同。但是,我的问题是当我创建一个 json 文件作为输出并保存文件时,生成的数据被编码为 un​​icode 而不是西班牙文本。我也尝试过解码 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()

【问题讨论】:

    标签: python mysql json


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答;这就是我想要保存数据的诀窍。
    • 太棒了!这就像一个魅力。任何人都知道为什么会这样以及为什么设置 encoding='utf8' 不会?例如在: with open(f'./hierarchy/{website}_api_category_tree.json', 'w', encoding='utf8')
    猜你喜欢
    • 2023-03-26
    • 2020-08-10
    • 2015-06-14
    • 2016-09-06
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    相关资源
    最近更新 更多