JSON edge cases

Negative indexes, escape matrix, numeric extremes, invalid-JSON error handling.

Version
Latest
v0.1.0 · latest 1 min read
On this page
  1. Scalar literal matrix
  2. Negative array indexes
  3. Escape matrix
  4. Numeric extremes
  5. Invalid JSON — catch it with DO/EXCEPTION

Scalar literal matrix#

sqlsource
SELECT 'null'::json, 'true'::json, '123'::json, '-123.456'::json, '1e10'::json, '"hello"'::json;
SELECT 'null'::jsonb, '1e-100'::jsonb, '-1e100'::jsonb;
SELECT jsonb_typeof('[]'::jsonb), jsonb_typeof('{}'::jsonb);  -- array | object

Negative array indexes#

sqlsource
SELECT '[10,20,30]'::jsonb -> 0;    -- 10
SELECT '[10,20,30]'::jsonb -> -1;   -- 30 (from the end)
SELECT '[10,20,30]'::jsonb ->> -1;  -- '30'
SELECT '[10,20,30]'::jsonb #> '{-1}';
SELECT '{"a":{"b":[{"c":42}]}}'::jsonb #>> '{a,b,0,c}';  -- '42'

Escape matrix#

sqlsource
SELECT '"quote: \"hello\""'::jsonb, '"slash: \/"'::jsonb, '"tab: \t"'::jsonb;
SELECT E'"unicode: \\u0041"'::jsonb;   -- "A", incl. surrogate pairs \uD83D\uDE00

Numeric extremes#

sqlsource
SELECT '1.0000000000000000000000001'::jsonb, '1e100'::jsonb;
SELECT '999999999999999999999999999999999999999999'::jsonb;

Invalid JSON — catch it with DO/EXCEPTION#

sqlsource
DO $$
BEGIN
  PERFORM '"bad: \q"'::jsonb;
EXCEPTION WHEN OTHERS THEN
  RAISE NOTICE 'EXPECTED INVALID ESCAPE: %', SQLERRM;
END $$;

Invalid escapes, short \u12 sequences, and malformed numbers raise — never silently coerce. Wrap ingestion casts in DO … EXCEPTION or validate with IS JSON first:

sqlsource
SELECT payload FROM events WHERE payload IS JSON;

Related: Operators · Functions · NULL

Was this page helpful?