postgres之jsonb属性的使用操作(curl post json请求)万万没想到

随心笔谈11个月前发布 admin
89 0



方法定义:

jsonb_set(target jsonb, path text[], new_value jsonb[, create_missing boolean])

参数:

:目标(jsonb类型的属性)

:路径,如果jsonb是数组‘{0,a}’表示在下标是0的位置更新a属性,如果不是数组,是对象,则写‘{a}’即可

:新值

选填参数:create_missing:jsonb字段不存在f1属性时创建,默认为true

返回:更新后的jsonb

jsonb_set(‘[, 2]

更新jsonb属性:

— attributes为jsonb类型字段(对象转成的json)
原值:

为jsonb插入属性:

— 执行后attributes字段中添加了platform:baidu
update user_test set attributes=attributes::jsonb || ”,'”baidu”‘);

查询

select value from json_each(”
结果:”b1″

补充一下吧

jsonb存储毫秒值字段
# 更新user表中attributes字段中的create_time字段为当前时间
update user_test
set attributes=jsonb_set(attributes,'{create_time}’,to_jsonb(extract(epoch from now())*1000), true)
EXTRACT(field FROM source)

field 表示取的时间对象,source 表示取的日期来源,类型为 timestamp、time 或 interval。

EXAMPLE:select extract(year from now());

查看现在距1970-01-01 00:00:00 UTC 的秒数

:新纪元时间 Epoch 是以 1970-01-01 00:00:00 UTC 为标准的时间,将目标时间与 1970-01-01 00:00:00时间的差值以秒来计算 ,单位是秒,可以是负值;

先看表结构:

create table person
(id int, — 唯一标识
label jsonb); — 人的标签数组(指明某人是哪个公司的),标签时一个一个的对象

label字段数据实例

[]

要求:写sql实现添加一个标签,删除一个标签,清空标签;

直接使用 || 符号将两个jsonb连接成一个jsonb

— 当label为null时
update person set label=”::jsonb;
— label不为null时运行
update person set label=”::jsonb || label

注意:当label为null时这样执行最后得到的也是null

这个比较简单,我直接设置为null

update person set label=null;

这个就比较麻烦一点,我用到了

-> ->> jsonb_array_elements() jsonb_build_array() array()

不熟悉这些符号和函数的用法的看:http://www.postgres.cn/docs/10/datatype-json.html

update person
set label=jsonb_build_array(
array( — 不使用该函数,当筛选出有多于2跳数据时会报错,因为jsonb_build_array函数只能有一个json
(select * from
(select jsonb_array_elements(label)j from person where id=1)as a
where (j->>’id’)::int <> 1) — 筛选出要删除的对象
)
)->0 — 如果不加这个你会得到两个[[]]的数组
where id=1;

以上就是我解决pg中操作jsonb数组的方法,希望能给大家一个参考,也希望大家多多支持脚本之家.

您可能感兴趣的文章:PostgreSQL 更新JSON,JSONB字段的操作postgresql 实现修改jsonb字段中的某一个值postgresql的jsonb数据查询和修改的方法如何获取PostgreSQL数据库中的JSON值

© 版权声明

相关文章