2012-07-03 119 views
2
在PostgreSQL和JSON解析文本類型列雙引號的轉義


我有以下表中PostgreSQL的定義:
通過傑克遜

 Column  |   Type   | Modifiers 
-----------------+------------------------+----------- 
id    | uuid     | not null 
entity_snapshot | text     | 
Indexes: 
    "pk_id" PRIMARY KEY, btree (id) 

我想存儲以下JSON字符串:

[ "org.test.MyUniqueId", {: "uuid" : "f4b40050-9716-4346-bf84-8325fadd9876": } ] 

對於一些測試,而不是這樣做使用傑克遜,我嘗試手動鍵入一個SQL,這裏是我的問題 - 我似乎無法得到正確的。
我現在的嘗試是:

insert into my_table(id,entity_snapshot) values ('d11d944e-6e78-11e1-aae1-52540015fc3f','[ \"org.test.MyUniqueId\", {: \"uuid\" : \"f4b40050-9716-4346-bf84-8325fadd9876\": } ]'); 

Procuedure看起來像什麼,我需要當我從表中選擇,但是當我嘗試使用傑克遜解析它,我得到一個錯誤的紀錄 -

org.apache.commons.lang.SerializationException: org.codehaus.jackson.JsonParseException: Unexpected character (':' (code 58)): was expecting double-quote to start field name 

不用說,如果通過我的java代碼插入相同的記錄,我可以解析它,當涉及到用人眼來查看記錄時,它對我來說看起來是一樣的。
你能告訴我在我的SQL插入語句中我錯了嗎?

+0

您可以使用sqldump寫在Java插入行和手動文本文件和比較什麼是與手動插入不同。 –

回答

3

雙引號內的單引號不需要進行轉義處理。

insert into my_table (id,entity_snapshot) 
values 
(
    'd11d944e-6e78-11e1-aae1-52540015fc3f', 
    '["org.test.MyUniqueId", {: "uuid" : "f4b40050-9716-4346-bf84-8325fadd9876": }]' 
); 

會工作得很好:

 
postgres=> create table my_table (id uuid, entity_snapshot text); 
CREATE TABLE 
Time: 34,936 ms 
postgres=> insert into my_table (id,entity_snapshot) 
postgres-> values 
postgres-> (
postgres(> 'd11d944e-6e78-11e1-aae1-52540015fc3f', 
postgres(> '["org.test.MyUniqueId", {: "uuid" : "f4b40050-9716-4346-bf84-8325fadd9876": }]' 
postgres(>); 
INSERT 0 1 
Time: 18,255 ms 
postgres=> 
6

您可以使用美元引用字符串常量。 詳情請看這裏Postgres documentation

在你的情況的查詢應該像

insert into my_table(id,entity_snapshot) values ('d11d944e-6e78-11e1-aae1-52540015fc3f',$$[ "org.test.MyUniqueId", {: "uuid" : "f4b40050-9716-4346-bf84-8325fadd9876": } ]$$);