简体   繁体   中英

Update json string value using postgresql

I have a column wich is varchar type, but inside I have json string values like

{"namme":"john", "email":"j@gmail.com", "cep":"0000"}

I want to update all rows changing "namme" for "name" like this:

{"name":"john", "email":"j@gmail.com", "cep":"0000"}

I've tried a query like this :

update lista_distribuicao
set mycolumn = mycolumn::jsonb - 'namme'
                          || jsonb_build_object('name',
                                                mycolumn->'namme')

Bu I get the following error:

[42883] ERROR: operator does not exist: jsonb - unknown Dica: No operator matches the given name and argument type(s). You might need to add explicit type casts.

You are close, the only thing missing is the here :

json_build_object('name',mycolumn::jsonb->'namme')

Working example :

CREATE TABLE test (
    te varchar
);

INSERT INTO test VALUES ('{"namme":"john", "email":"j@gmail.com", "cep":"0000"}');

UPDATE test
SET te = te::jsonb - 'namme' || jsonb_build_object('name', te::jsonb->'namme');

SELECT te
FROM test;

Be careful, running this query twice will set the name column to NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM