pet*_*rko 3 postgresql json type-conversion
我在数据库中有一个表query_config,它将包含用于查询的脚本以及其他配置值.这就是我使用json类型的原因.表如下:
CREATE TABLE query_config
(
id integer,
execute_query json
);
Run Code Online (Sandbox Code Playgroud)
在这个表中,我想插入例如:
INSERT INTO query_config(id, execute_query)
VALUES (4, ('{"query": ' ||
'"select *
from tests
where tests.id > 5
order by moment desc"}')::json);
Run Code Online (Sandbox Code Playgroud)
但我一直收到错误:
ERROR: invalid input syntax for type json
DETAIL: Character with value 0x0a must be escaped.
Run Code Online (Sandbox Code Playgroud)
我做错了什么,如何逃脱换行符呢?
使用to_json,使其有效的JSON,并dollar quoting因此它会吞噬在查询中的任何文本
select format('{%s: %s}',
to_json('query'::text),
to_json($query$
select *
from tests
where tests.id > 5
order by moment desc
$query$::text)
)::json;
format
---------------------------------------------------------------------------------------------------------------------
{"query": "\n select *\n from tests\n where tests.id > 5\n order by moment desc\n "}
Run Code Online (Sandbox Code Playgroud)
http://www.postgresql.org/docs/current/static/functions-json.html#FUNCTIONS-JSON-TABLE
http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS
格式化功能只是为了让眼睛更容易
http://www.postgresql.org/docs/current/static/functions-string.html#FUNCTIONS-STRING-OTHER
如果您删除新行,换句话说,将 json 值放在一行上,它将起作用,例如:
INSERT INTO query_config(id, execute_query)
VALUES (4, ('{"query":' || '"select * from tests where tests.id > 5 order by moment desc"}')::json);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9048 次 |
| 最近记录: |