Created
July 18, 2019 10:34
-
-
Save igrek8/0ee200bf0bad490fa36f54eee863c242 to your computer and use it in GitHub Desktop.
Postgres: Flatten JSON keys and keys paths
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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