python将unicode转换为可读字符

时间:2014-09-12 15:52:00

标签: python postgresql unicode

我使用python 2.7和psycopg2连接到postgresql

我从包含'Aéropostale'字符串的来源读取了大量数据。然后我将它存储在数据库中。但是,在postgresql中它最终为'A\u00e9ropostale'。但我希望它被存储为'Aéropostale'。

postgresql数据库的编码是utf-8。

请告诉我如何存储实际字符串'Aéropostale'。 我怀疑问题是在python中发生的。请指教。

编辑:

这是我的数据源

response_json = json.loads(response.json())

响应是通过服务电话获得的,如下所示:

print(type(response.json())
>> <type'str'>
print(response.json())
>> {"NameRecommendation": ["ValueRecommendation": [{"Value": "\"Handmade\""}, { "Value": "Abercrombie & Fitch"}, {"Value": "A\u00e9ropostale"}, {"Value": "Ann Taylor"}}]

从上面的数据,我的目标是构建一个所有ValueRecommendation.Value的列表并存储在postgresql json数据类型列中。所以我要存储的python等价列表是

py_list = ["Handmade", "Abercrombie & Fitch",  "A\u00e9ropostale", "Ann Taylor"]

然后我使用json.dumps()

将py_list转换为json表示
json_py_list = json.dumps(py_list)

最后,要插入,我使用psycopg2.cursor()和mogrify()

conn = psycopg2.connect("connectionString")
cursor = conn.cursor()
cursor.execute(cursor.mogrify("INSERT INTO table (columnName) VALUES (%s), (json_py_list,)))

正如我前面提到的,使用上面的逻辑,带有像è这样的特殊字符的字符串将被存储为utf8字符代码。  请发现我的错误。

1 个答案:

答案 0 :(得分:1)

json.dumps默认转义非ASCII字符,因此其输出可以在非Unicode安全的环境中工作。你可以用以下方式关闭它:

json_py_list = json.dumps(py_list, ensure_ascii=False)

现在您将获得UTF-8编码的字节(除非您使用encoding=进行更改),因此您需要确保数据库连接使用该编码。

一般来说,它不应该有任何区别,因为这两种形式都是有效的JSON,即使ensure_ascii关闭,仍然有一些字符会被\u - 编码。

相关问题