PostgreSQL 操作JSON类型
1.json和jsonb的操作符
操作符 | 右操作数类型 | 描述 | 示例 | 结果 |
---|---|---|---|---|
-> | int | 获取JSON数组元素(索引从0开始) | select ‘[{“a”:“foo”},{“b”:“bar”},{“c”:“baz”}]’::json->2; | {“c”:“baz”} |
-> | text | 通过键获取值 | select ‘{“a”: {“b”:“foo”}}’::json->‘a’; | {“b”:“foo”} |
->> | int | 获取JSON数组元素为 text | select ‘[1,2,3]’::json->>2; | 3 |
->> | text | 通过键获取值为text | select ‘{“a”:1,“b”:2}’::json->>‘b’; | 2 |
#> | text[] | 在指定的路径获取JSON对象 | select ‘{“a”: {“b”:{“c”: “foo”}}}’::json#>’{a,b}’; | {“c”: “foo”} |
#>> | text[] | 在指定的路径获取JSON对象为 text | select ‘{“a”:[1,2,3],“b”:[4,5,6]}’::json#>>’{a,2}’; | 3 |
2.jsonb额外操作符
操作符 | 右操作数类型 | 描述 | 示例 | 结果 |
---|---|---|---|---|
@> | jsonb | 左侧json最上层的值是否包含右边json对象 | select ‘{“a”:{“b”:2}}’::jsonb @> ‘{“b”:2}’::jsonb; select ‘{“a”:1, “b”:2}’::jsonb @> ‘{“b”:2}’::jsonb; | f t |
<@ | jsonb | 左侧json对象是否包含于右侧json最上层的值内 | select ‘{“b”:2}’::jsonb <@ ‘{“a”:1, “b”:2}’::jsonb; | t |
? | text | text是否作为左侧Json对象最上层的键 | select ‘{“a”:1, “b”:2}’::jsonb ? ‘b’; | t |
?| | text[] | text[]中的任一元素是否作为左侧Json对象最上层的键 | select ‘{“a”:1, “b”:2, “c”:3}’::jsonb ?| array[‘b’, ‘c’]; | t |
?& | text[] | text[]中的所有元素是否作为左侧Json对象最上层的键 | select ‘[“a”, “b”]’::jsonb ?& array[‘a’, ‘b’]; | t |
|| | jsonb | 连接两个json对象,组成一个新的json对象 | select ‘[“a”, “b”]’::jsonb || ‘[“c”, “d”]’::jsonb; | [“a”, “b”, “c”, “d”] |
- | text | 删除左侧json对象中键为text的键值对 | select ‘{“a”: “b”}’::jsonb - ‘a’; | {} |
- | integer | 删除数组指定索引处的元素,如果索引值为负数,则从右边计算索引值。如果最上层容器内不是数组,则抛出错误。 | select ‘[“a”, “b”]’::jsonb - 1; | [“a”] |
#- | text[] | 删除指定路径下的域或元素(如果是json数组,且整数值是负的,则索引值从右边算起) | select ‘[“a”, {“b”:1}]’::jsonb #- ‘{1,b}’; | [“a”, {}] |