2017-04-19 24 views
1

我使用的是Postgres 9.5和我有一個列類型「json的」的(「信息」)......我想這樣做插入:使用PostgreSQL,我如何在json列中轉義「」?

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

,但我得到這個錯誤:

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

它將\+解釋爲轉義序列,但我真的希望將其作爲我的價值的一部分。

+0

請幫助弄清楚它所屬的位置,並將其標記爲將其遷移到[dba.se]。 –

回答

2

一般來說,

  • ,如果你有鍵和值使用jsonb_build_object構造對象
  • 如果你正在寫一個文字JSON對象從字符串施放,那麼它必須是正確的;正確的JSON字符串需要轉義\

說明

PostgreSQL的不引用這樣的:它只是JSON執行力度以下RFC 7159

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); 
+0

這是有效的,因爲它會逃脫\,但是...在數據庫列中,我現在有一個額外的\此條目(即((\\ +)[0-9] +))當我檢索這個數據。有沒有辦法讓它恢復原始的非轉義價值? – user3228515

相關問題