表1:json操作符
操作符 | 描述 | 例子 | 结果 |
|| | jsonb追加 | select '{"name":"duke"}'::jsonb||'{"age":"18"}'::jsonb | {"age": "18", "name": "duke"} |
jsonb更新,也可以用jsonb_set函数 | select '{"name":"duke"}'::jsonb || '{"name":"marry"}'::jsonb; | {"name": "marry"} | |
- | jsonb删除 | select '{"age": "18", "name": "duke"}'::jsonb - 'age' | {"name": "duke"} |
#- | jsonb删除,通常用于删除嵌套的json数据 | select '{"name": "duke", "contain":{"age":18,"gender":"男"}}'::jsonb #- '{contain,gender}'::text[]; 删除指定嵌套键值 | {"name": "duke", "contain": {"age": 18}} |
select '{ "name": "duke","contain":[1,2,3]}'::jsonb #- '{contain,1}'::text[]; 删除嵌套的指定位置的值(索引从0开始) | {"name": "duke", "contain": [1, 3]} | ||
@> | 判断是否包含 | SELECT '{"name": "duke", "age": 18}'::jsonb @> '{"name": "duke"}'::jsonb; 右边具有一个单一键值对的对象被包含在左边的对象中
| ?column? ---------- t (1 行记录) |
包含一个顶层键和一个空对象: SELECT '{"duke": {"age": 18}}'::jsonb @> '{"duke": {}}'::jsonb;
| ?column? ---------- t (1 行记录) | ||
? | 判断字符串是否存为json的键 | SELECT '{"name": "duke"}'::jsonb ? 'name'; | ?column? ---------- f (1 行记录) |
表2:json与jsonb函数简介
函数 | 描述 | 例子 | 结果 |
jsonb_set(j1 jsonb,path text[],j2 jsonb[,create_missing boolean]) | target指源jsonb数据,path指路径,j2指更新后的键值,create_missing值为true表示如果键不存在则添加,create——missing值为false表示如果键不存在则不添加。 | select jsonb_set('{"name":"duke","age":18}'::jsonb,'{age}','20'::jsonb,false); | jsonb_set ------------------------ {"age": 20, "name": "duke"} |
select jsonb_set('{"name":"duke","age":18}'::jsonb,'{sex}','"男"'::jsonb,true); | jsonb_set ------------------------ {"age": 18, "sex": "男", "name": "duke"} | ||
json_each(json) | 扩展最外层的json成为一组键/值结果集 | select * from json_each('{"name":"duke","age":18}'::json); | key | value ------+-------- name | "duke" age | 18 |
json_each_text(json) | 扩展最外层的json成为一组键/值结果集,以文本返回 | select * from json_each_text('{"name":"duke","age":18}'::json); | key | value ------+------- name | duke age | 18 |
row_to_json(table) | 将行作为json数据进行返回 | select row_to_json(t_json) from t_json; | row_to_json ------------------------- {"id":1,"name":"duke"} {"id":2,"name":"marry"} (2 行记录)
|
json_object_keys(json) | 返回最外层的json对象中的键集合 | select json_object_keys('{"name":"duke","age":18}'::json); | json_object_keys ------------------ name age (2 行记录) |