JSON中的Postgresql“转义序列”\\&“无效”

2024-10-04 01:36:45 发布

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

我在Postgresql中以JSON结构存储HTML和各种文本位,使用Python和pg8000库编写。我发现我经常会遇到类似以下的错误:

pg8000.core.ProgrammingError: {'S': 'ERROR', 'V': 'ERROR', 'C': '22P02', 'M': 'invalid input syntax for type json', 'D': 'Escape sequence "\\&" is invalid.', 'W': 'JSON data, line 1: ...Ga,"'"));-1!=a.indexOf("\\&...', 'F': 'json.c', 'L': '951', 'R': 'json_lex_string'}

因此,要去除这些代码,我有以下非常慢的代码,我必须不断添加特定的“无效转义序列”:

    def filter_values(value: Any) -> Any:
        if isinstance(value, list):
            return list(map(filter_values, value))
        if isinstance(value, dict):
            return {k:filter_values(v) for k, v in value}
        if isinstance(value, str):
            stripped = value.strip().replace('\\u0000', '').replace('\u0000', '').replace(u'\u0000', '')
            while '\\-' in stripped:
                stripped = stripped.replace('\\-', '-')
            while '\\+' in stripped:
                stripped = stripped.replace('\\+', '+')
            while '\\E' in stripped:
                stripped = stripped.replace('\\E', 'E')
            while '\\&' in stripped:
                stripped = stripped.replace('\\&', '&')
            return stripped
        return value

如果我不能去掉所有的\,那会破坏json(比如\")。一定有更好的办法。在JSON Postgresql blob中正确转义字符的规则是什么


Tags: injsonreturnifvaluepostgresqlfilterreplace