2017-12-08 3 views
1

入れ子になったJSON構造の複数の場所にある特定の文字列を、postgresテーブルにjsonbとして格納されている特定の文字列にグローバルに置き換える必要があります。たとえば:Postgres JSONBフィールドでグローバルに置き換えます

{ 
    "location": "tmp/config", 
    "alternate_location": { 
    "name": "config", 
    "location": "tmp/config" 
    } 
} 

は...となるべき:私が試した

{ 
    "location": "tmp/new_config", 
    "alternate_location": { 
    "name": "config", 
    "location": "tmp/new_config" 
    } 
} 

UPDATE files SET meta_data = to_json(replace(data::TEXT, 'tmp/config', 'tmp/new_config')); 

は、残念ながら、これはトリプルエスケープ引用符で、不正な形式のJSONになります。

どのようにすればいいですか?

+0

これが有効なJSONではありません。 – klin

+0

@klin、whoops、私は例jsonを有効にしました。 – crowhoplaminar

答えて

1

は例えば、jsonb代わりのto_json()に、単純なキャストを使用してください:

with files(meta_data) as (
values(
'{ 
    "location": "tmp/config", 
    "alternate_location": { 
    "name": "config", 
    "location": "tmp/config" 
    } 
}'::jsonb) 
) 

select replace(meta_data::text, 'tmp/config', 'tmp/new_config')::jsonb 
from files; 

               replace             
-------------------------------------------------------------------------------------------------------- 
{"location": "tmp/new_config", "alternate_location": {"name": "config", "location": "tmp/new_config"}} 
(1 row) 
関連する問題