Skip to content

Instantly share code, notes, and snippets.

@brito
Created March 9, 2022 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brito/69cf4cb3f429d6c573e6412f1c9c854e to your computer and use it in GitHub Desktop.
Save brito/69cf4cb3f429d6c573e6412f1c9c854e to your computer and use it in GitHub Desktop.
recursive introspection: flatten (json) → (key, value, json_type)
/*
Flatten JSON tables
*/
create or replace function flatten_json(data jsonb)
returns table (
key text,
value jsonb,
json_type text)
as
$$
with recursive flatten (key, value, json_type) as (
select key, value, jsonb_typeof(value)
from jsonb_each(data)
union all
(with typed_values as (table flatten)
select concat_ws('.', f.key, g.key), g.value, jsonb_typeof(g.value)
from typed_values f,
jsonb_each(f.value) g
where json_type = 'object'
union all
select concat_ws('.', f.key, index), array_value, jsonb_typeof(array_value)
from typed_values f,
jsonb_array_elements(value)
with ordinality g(array_value, index)
where json_type = 'array'))
select *
from flatten
where json_type !~ 'object|array|null'
and value #>> '{}' <> ''
$$
language sql
stable;
alter function flatten_json owner to postgres;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment