On 28th of March 2022, Andrew Dunstan
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.