2017-05-08 80 views
0

我嘗試從包含json行的表中加載一些數據。
有一個字段可以包含特殊字符\ t和\ r,並且我想將它們保留在新表中。postgresql json列錯誤字符的值必須轉義

這裏是我的文件:

{"text_sample": "this is a\tsimple test", "number_sample": 4} 

這裏是我做的:

Drop table if exists temp_json; 
Drop table if exists test; 
create temporary table temp_json (values text); 

copy temp_json from '/path/to/file'; 

create table test as (select 
     (values->>'text_sample') as text_sample, 
     (values->>'number_sample') as number_sample 
     from (
      select replace(values,'\','\\')::json as values 
      from temp_json 
     ) a); 

我不斷收到此錯誤:

ERROR: invalid input syntax for type json 
DETAIL: Character with value 0x09 must be escaped. 
CONTEXT: JSON data, line 1: ...g] Objection to PDDRP Mediation (was Re: Call for... 

如何,我需要逃避這些字符?
非常感謝

+0

發佈包含違規的樣本數據行。 –

+0

我更新了所有需要的細節 –

+1

'copy temp_json from program'sed -e''s/\\/\\\\/g''/ path/to/file';'? – Abelisto

回答

0

將json轉換爲文本,而不是從json獲取文本值。例如:

t=# with j as (
     select '{"text_sample": "this is a\tsimple test", "number_sample": 4}'::json v 
) 
select v->>'text_sample' your, (v->'text_sample')::text better 
from j; 
      your    |   better 
-----------------------------+-------------------------- 
this is a  simple test | "this is a\tsimple test" 
(1 row) 

,避免×09錯誤,請嘗試使用

replace(values,chr(9),'\t') 

在你的榜樣,你替換反斜槓+ T,而不是實際的chr(9) ...

+0

我得到同樣的錯誤,當我嘗試這樣做對整個表'其中j爲( 選擇值:: JSON V與temp_json \t \t) 選擇N - >>「text_sample」你,(V->」 text_sample'):: text better從j更新 ; ' –

+0

嘗試regexp_replace(values,'\ t','\\ t','g')?..您的示例沒有引發錯誤,所以我不確定是什麼問題 - 您可能有chr(9 )在數值中,而不是'\ t'? –

+0

我不想明確地逃避選項卡,因爲它可能有任何其他類型的特殊字符,我正在尋找一種通用的方式來做那 –

1

複製文件csv帶有不同的引號字符和分隔符:

drop table if exists test; 
create table test (values jsonb); 
\copy test from '/path/to/file.csv' with (format csv, quote '|', delimiter ';'); 

select values ->> 'text_sample', values ->> 'number_sample' 
from test; 
      ?column?   | ?column? 
-----------------------------+---------- 
this is a  simple test | 4 
相關問題