gpt4 book ai didi

json - 使用 PostgreSQL,如何在 json 列中转义 "\"?

转载 作者:行者123 更新时间:2023-11-29 11:44:41 25 4
gpt4 key购买 nike

我正在使用 Postgres 9.5 并且我有一个类型为“json”的列(“信息”)...我正在尝试插入:

INSERT INTO table ( info )
VALUES (
'{"entry":"((\+)[0-9]+)"}'
)

但是我得到这个错误:

ERROR:  invalid input syntax for type json
DETAIL: Escape sequence "\+" is invalid.

它将 \+ 解释为转义序列,但我实际上希望将其作为我值的一部分。

最佳答案

一般而言,

  • 如果您有键和值,请使用 jsonb_build_object构建对象
  • 如果您正在编写一个文字 JSON 对象以从字符串转换,那么它必须是正确的;正确的 JSON 字符串需要转义 \

说明

PostgreSQL 没有引用这个:它只是 RFC 7159 之后的 JSON 实现.

A string begins and ends with quotation marks. All Unicode characters may be placed within the quotation marks, except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F). [... ] So, for example, a string containing only a single reverse solidus character may be represented more compactly as "\\".

所以它在字面形式上看起来是这样的。

CREATE TABLE tbl
AS
SELECT '{"entry":"((\\+)[0-9]+)"}'::jsonb AS info;

PostgreSQL 中的美元报价需要无转义,但在这里无济于事,

Notice that inside the dollar-quoted string, single quotes can be used without needing to be escaped. Indeed, no characters inside a dollar-quoted string are ever escaped: the string content is always written literally. Backslashes are not special, and neither are dollar signs, unless they are part of a sequence matching the opening tag.

所以这将起作用,因为 \+ 不是 JSON 中的有效字符串。不过,如果我们不使用 json 类型,它会起作用。

SELECT '{"key":"\"}'::jsonb;
ERROR: invalid input syntax for type json
LINE 1: SELECT '{"key":"\"}'::jsonb;
^
DETAIL: Token ""\"}" is invalid.
CONTEXT: JSON data, line 1: {"key":"\"}

但是,您可以使用 to_jsonb() 对字符串进行 JSON 转义。

SELECT FORMAT( $${%s:%s}$$, to_jsonb(k), to_jsonb(v) )::jsonb
FROM ( VALUES
('key', '\' )
) AS t(k,v);

但是,即使这是一个坏主意,因为如果你有键和值,你可以使用 json_build_object

SELECT jsonb_build_object( k, v )
FROM ( VALUES
('key', '\' )
) AS t(k,v);

关于json - 使用 PostgreSQL,如何在 json 列中转义 "\"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43502806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com