官方文档给出的示例(jsonb数组):
jsonb_set('[{"f1":1,"f2":null},2,null,3]', '{0,f1}','[2,3,4]', false)
结果:[{"f1":[2,3,4],"f2":null},2,null,3]
jsonb_set('[{"f1":1,"f2":null},2]', '{0,f3}','[2,3,4]')
结果:[{"f1": 1, "f2": null, "f3": [2, 3, 4]}, 2]
更新jsonb属性:
-- attributes为jsonb类型字段(对象转成的json)
原值:{"a":"1"}
update user_test set attributes = jsonb_set(attributes,'{a}','"0"'::jsonb, false) where id = '8888';
执行后:{"a":"0"}
为jsonb插入属性:
-- 执行后attributes字段中添加了platform:baidu
update user_test set attributes = attributes::jsonb || '{"platform":"baidu"}'::jsonb;
或者:
update user_test set attributes = jsonb_set(attributes, '{platform}','"baidu"');
查询
select value from json_each('{"a":"foo", "b":"bar"}') where key = 'a'
select * from json_object_keys('{"a":"foo", "b":"bar"}')
select * from json_object_keys('{"f1":"abc","f2":{"f3":"a", "f4":"b"}}')
select * from json_object_keys(from ci_type.attributes);--错误
select * from to_jsonb('"a":1,"b":2')
select '{"a":1,"b":2}'::json->>'b' --获取jsonb中对应键的值(文本)
--select * from json_each( to_jsonb(select distinct attributes from ci_type ) )
--select to_jsonb(select distinct attributes from ci_type )
--扩展字段提取相应属性的值
select attributes :: json->>'instanceType' from ci_type
-- 属性值转为jsonb
select to_jsonb('id:'||id::text) from ci
--jsonb添加属性,删除属性
select '{"a":"foo", "b":"bar"}'::jsonb || '{"c":"fc", "d":"bdd"}'::jsonb--添加
select '{"a":"foo", "b":"bar"}'::jsonb -'c'-'d'-'a'||'{"a":2}'--删除
select '{"a": "b","c":3}'::jsonb - 'a'
-- 根据路径获取json对象:#>
SELECT '{"a":1,"b":{"ba":"b1","bb":"b2"},"c":3}'::JSON #> '{b,ba}'
结果:"b1"
SELECT '{"a":1,"b":{"ba":"b1","bb":"b2"},"c":3}'::JSON #> '{b}'
结果:{"ba":"b1","bb":"b2"}
-- 根据路径获取json对象为text:#>>
SELECT '{"a":1,"b":{"ba":"b1","bb":"b2"},"c":3}'::JSON #>> '{b,ba}'
结果:"b1"
# 更新user表中attributes字段中的create_time字段为当前时间
update user_test
set attributes = jsonb_set(attributes,'{create_time}',to_jsonb(extract(epoch from now())*1000), true)
extract(epoch from now())*1000 获取毫秒值
EXTRACT(field FROM source)
field 表示取的时间对象,source 表示取的日期来源,类型为 timestamp、time 或 interval。
EXAMPLE:select extract(year from now());
extract(epoch from now())查看现在距1970-01-01 00:00:00 UTC 的秒数
epoch:新纪元时间 Epoch 是以 1970-01-01 00:00:00 UTC 为标准的时间,将目标时间与 1970-01-01 00:00:00时间的差值以秒来计算 ,单位是秒,可以是负值;