Introduction to json and jsonn Operators of PostgresSQL
Posted By : Gursahib Singh | 27-Sep-2018
There are times where we require to operate on
JSON operators:
1. "->"
It provides the json array element indexed from 0.The right hand operand type is "integer"
Example- SELECT '[{"a":"foo"},{"b":"bar"},{"c":"baz"}]'::json->2
Result - {"c":"baz"}
2. "->"
It provides the json object field by key.The right hand operand type is "text"
Example- SELECT '{"a": {"b":"foo"}}'::json->'a'
Result - {"b":"foo"}
3. "->>"
It provides the json array element as text.The right hand operand type is "text"
Example- '{"a":1,"b":2}'::json->>'b'
Result - 2
4. "->>"
It provides the json object field as text.The right hand operand type is "int"
Example- SELECT '[1,2,3]'::json->>2
Result - 3
5. "#>"
It provides the json object field at specified path as text.The right hand operand type is "text[]"
Example- SELECT '{"a":[1,2,3],"b":[4,5,6]}'::json#>>'{a,2}'
Result - {"c": "foo"}
6. "#>>"
It provides the json object field at specified path.The right hand operand type is "text[]"
Example- SELECT '{"a":[1,2,3],"b":[4,5,6]}'::json#>>'{a,2}'
Result - 3
JSONB operators
1. "@>"
It returns the boolean value specifying whether the right json value contains within the left value. The right hand operand type is "jsonb"
Example- SELECT '{"a":1, "b":2}'::jsonb @> '{"b":2}'::jsonb2
Result - true
2. "<@"
It returns the boolean value specifying whether the left json value contains within the right value. The right hand operand type is "jsonb.
Example- SELECT '{"b":2}'::jsonb <@ '{"a":1, "b":2}'::jsonb
Result - true
3. "?"
It returns the boolean value specifying whether the key element string exists within the
Example- SELECT '{"a":1, "b":2}'::jsonb ? 'b'
Result - true
4. "?|"
.
It returns the boolean value specifying whether the key strings exist. The right-hand operand type is "text[]".
Example- SELECT '{"a":1, "b":2, "c":3}'::jsonb ?| array['b', 'c']
Result - true
5. "?&"
It returns the boolean value specifying whether any of these key element string exists.The right hand operand type is "text[]".
Example- true
This is the basic introduction of how to use
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Gursahib Singh
Gursahib is a software developer having key skills in J2SE and J2EE. His hobbies are playing chess, reading and learning new softwares.