Waiting for PostgreSQL 15 – IS JSON predicate

On 28th of March 2022, Andrew Dunstan
New Blog Post

Title: Waiting for PostgreSQL 15 – IS JSON predicate

On 28th of March 2022, Andrew Dunstan committed patch:

IS JSON predicate
 
This patch intrdocuces the SQL standard IS JSON predicate. It operates
on text and bytea values representing JSON as well as on the json and
jsonb types. Each test has an IS and IS NOT variant. The tests are:
 
IS JSON [VALUE]
IS JSON ARRAY
IS JSON OBJECT
IS JSON SCALAR
IS JSON  WITH | WITHOUT UNIQUE KEYS
 
These are mostly self-explanatory, but note that IS JSON WITHOUT UNIQUE
KEYS is true whenever IS JSON is true, and IS JSON WITH UNIQUE KEYS is
true whenever IS JSON is true except it IS JSON OBJECT is true and there
are duplicate keys (which is never the case when applied to jsonb values).
 
Nikita Glukhov
 
Reviewers have included (in no particular order) Andres Freund, Alexander
Korotkov, Pavel Stehule, Andrew Alsup, Erik Rijkers, Zihong Yu,
Himanshu Upadhyaya, Daniel Gustafsson, Justin Pryzby.
 
Discussion: https://postgr.es/m/cd0bb935-0158-78a7-08b5-904886deac4b@postgrespro.ru

This is next in series of patches adding more and more of SQL/JSON functionality to Pg.

This time we get checks/predicates.

Generally they will return true/false depending on what's on the left. Let's see it in action:

=$ select '1' IS JSON, 'ab' IS JSON;
 ?column? | ?column? 
----------+----------
 t        | f
(1 row)

Obviously if I'd run IS JSON on real json value, it would be always true:

=$ select json_array(1, 2, 'a') is json;
 ?column? 
----------
 t
(1 row)

But we can now easily check for type of the json value:

=$ select v, v is json array as json_array, v is json object as json_object, v is json scalar as json_scalar
from unnest(array['12', '"abc"', '[1,2,3]', '{"a":12}']) v;
    v     | json_array | json_object | json_scalar 
----------+------------+-------------+-------------
 12       | f          | f           | t
 "abc"    | f          | f           | t
 [1,2,3]  | t          | f           | f
 {"a":12} | f          | t           | f
(4 rows)

Pretty cool. There is also “JSON WITH UNIQUE KEYS", which works like this:

=$ select v, v is json with UNIQUE keys
from unnest(array['12', '"abc"', '[1,2,3]', '{"a":12,"b":23}', '{"a":12,"a":23}']) v;
        v        | ?column? 
-----------------+----------
 12              | t
 "abc"           | t
 [1,2,3]         | t
 {"a":12,"b":23} | t
 {"a":12,"a":23} | f
(5 rows)

Looks really nice, and will make queries that work on json more readable. Thanks to all involved.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.