Skip to content

Instantly share code, notes, and snippets.

@igrek8
Created July 18, 2019 10:34
Show Gist options
  • Save igrek8/0ee200bf0bad490fa36f54eee863c242 to your computer and use it in GitHub Desktop.
Save igrek8/0ee200bf0bad490fa36f54eee863c242 to your computer and use it in GitHub Desktop.
Postgres: Flatten JSON keys and keys paths
WITH RECURSIVE doc_key_and_value_recursive (
KEY,
value
) AS (
SELECT
t.key,
t.value
FROM
stories_collection AS item,
json_each(item.data) AS t
WHERE
item.id = 46
UNION ALL
SELECT
CONCAT(doc_key_and_value_recursive.key, '.', t.key),
t.value
FROM
doc_key_and_value_recursive,
json_each(
CASE WHEN json_typeof(doc_key_and_value_recursive.value) <> 'object' THEN
'{}'::JSON
ELSE
doc_key_and_value_recursive.value
END) AS t
) SELECT DISTINCT
KEY
FROM
doc_key_and_value_recursive
WHERE
json_typeof(doc_key_and_value_recursive.value)
NOT IN ('array', 'object')
ORDER BY
KEY
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment