【问题标题】:Searching on json encoded string in Postgres with Python使用 Python 在 Postgres 中搜索 json 编码的字符串
【发布时间】:2013-08-11 20:05:31
【问题描述】:

我有一个类似这样的数据库查询,我在 Postgres 数据库上用 Python 执行:

"Select * from my_tbl where big_string like '%Almodóvar%'"

但是,在我搜索 Almodóvar 的列中,表示为“Almod\u00f3var”,因此查询不返回任何内容。

如何使两个字符串匹配?更愿意在 Python 端使用 Almodóvar 而不是数据库中的列,但我很灵活。

cmets 提示的其他信息:

数据库使用 UTF-8。我正在查询的字段是从外部 API 获取的。数据作为 json 以 RESTfully 方式检索,然后在 json.dump 之后插入到数据库的文本字段中。

由于数据包含大量外来名称和字符,因此使用它一直是一系列与编码相关的难题。如果有一个灵丹妙药可以让这些数据与 Python 配合得很好,我将非常感激知道那是什么。

更新 2:

看起来是 json 编码让我感到困惑。

print json.dumps("Almodóvar")

产量

"Almod\u00f3var"

这是我在查看原始数据时看到的。但是,当我使用 json.dumps 来构造这个时:

"Select * from my_tbl where big_string like '%Almod\u00f3var%'"

查询仍然没有产生任何结果。我被难住了。

【问题讨论】:

    标签: python json postgresql encoding


    【解决方案1】:

    来自帮助(json.dumps):

    If ``ensure_ascii`` is false, all non-ASCII characters are not escaped, and
    the return value may be a ``unicode`` instance. See ``dump`` for details.
    

    来自帮助(json.loads):

    If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
    other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
    must be specified. Encodings that are not ASCII based (such as UCS-2)
    are not allowed and should be decoded to ``unicode`` first.
    

    所以试试类似的东西

    >>> js = json.dumps("Almodóvar", ensure_ascii=False)  
    >>> res = json.loads(js, encoding="utf-8")
    >>> print res
    Almodóvar
    

    【讨论】:

    • 这很有帮助。看起来最好的办法是使用 ensure_ascii=False 更新数据库中的转储,然后看看情况如何。感谢您的详细解释。这可能会解决我的很多问题。第一个错误可能是在没有编码参数的情况下加载 json。将针对我当前的问题对此进行测试,如果可行,请接受此答案。
    • 我创建了一个新列,其中包含根据您的帖子加载和转储的数据,并且能够执行我的问题中提到的搜索。谢谢!
    【解决方案2】:

    您的问题似乎来自您的查询之前的一步。从您从 Web 服务检索数据的时间开始。可能是:

    • 在您与 Web 服务通信期间,编码未设置为 UTF-8。
    • tmdb.org 端的编码不是 UTF-8(我不确定)。

    我会先从第二种可能性开始研究这两点。

    【讨论】:

    • 是的,我认为我的错误是在未设置编码参数的情况下从服务加载数据。从那以后就出现了一系列编码问题。
    【解决方案3】:

    将你的 postgres 表的字符编码设置为 utf-8,然后它将与 python 顺利集成。无需来回转换。您的问题看起来像是您的 python 代码和数据库使用了两种不同的编码。

    编辑:Almod\u00f3var 在我看来就像 windows 代码页 1252。

    【讨论】:

    • 出于好奇,如果他已经插入了值并表示为Almod\u00f3var,例如,更改数据库的编码会将这些先前插入的值的表示更改为Almodóvar。还是他必须进行一些处理?
    • 我已经确认数据库的编码已经是UTF-8了。将使用有关数据的更多信息更新我的问题。
    猜你喜欢
    • 2020-04-12
    • 2020-03-22
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 2018-11-26
    • 1970-01-01
    • 2015-12-24
    相关资源
    最近更新 更多