【问题标题】:postgresql text to json conversionpostgresql 文本到 json 转换
【发布时间】:2014-11-10 08:42:21
【问题描述】:

我在数据库中有一个表query_config,其中将包含用于查询的脚本,以及其他配置值​​。这就是我使用 json 类型的原因。 如下表:

CREATE TABLE query_config 
(
   id integer, 
   execute_query json 
); 

在这个表中我想插入例如:

INSERT INTO query_config(id, execute_query)
    VALUES (4, ('{"query": ' || 
    '"select *
    from tests
    where tests.id > 5
    order by moment desc"}')::json);

但我不断收到错误:

ERROR: invalid input syntax for type json 
DETAIL: Character with value 0x0a must be escaped.

请问我做错了什么以及如何转义换行符?

【问题讨论】:

    标签: json postgresql type-conversion


    【解决方案1】:

    使用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    "}
    

    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

    【讨论】:

      【解决方案2】:

      如果您删除新行,它将起作用,换句话说,将 json 值放在一行中,例如:

      INSERT INTO query_config(id, execute_query)
          VALUES (4, ('{"query":' || '"select * from tests where tests.id > 5 order by moment desc"}')::json);
      

      【讨论】:

      • 是的,这是一个选项,但可能需要更改将存储在那里的代码,因此我想保留换行符。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      相关资源
      最近更新 更多