修改Postgres中JSONB中字段的数据类型

时间:2017-02-17 18:09:46

标签: postgresql jsonb

我有一个带有JSON的JSONB列,如下所示:

  

{“id”:“3”,“username”:“abcdef”}

有没有办法将JSON更新为:

  

{“id”:3,“username”:“abcdef”}

2 个答案:

答案 0 :(得分:0)

select json_build_object('id',CAST(j->>'id' AS NUMERIC),'username',j->>'username')::jsonb  from (
    select '{"id" : "3", "username" : "abcdef"}' :: jsonb AS j
)t

答案 1 :(得分:0)

使用concatenate operator ||更新jsonb列,例如:

create table example(id int, js jsonb);
insert into example values
(1, '{"id": "3", "username": "abcdef"}');

update example
set js = js || jsonb_build_object('id', (js->>'id')::int)
returning *;

 id |               js                
----+---------------------------------
  1 | {"id": 3, "username": "abcdef"}
(1 row)