Lab setup
CREATE TABLE my_table(data json);
INSERT INTO my_table(data) VALUES
('{"key_a": "value_x"}'),
('{"key_a": "value_x"}'),
('{"key_a": "value_y"}'),
('{"key_a": "value_z"}'),
('{"key_b": "value_x"}'),
('{"key_c": "value_y"}'),
('{"key_d": "value_y"}');
json_each
expands the outermost JSON object into a set of key/value pairs. The returned value will be of type text.
SELECT entry.key, entry.value FROM my_table, json_each_text(my_table.data) AS entry;
key | value |
---|
key_a | value_x |
key_a | value_x |
key_a | value_y |
key_a | value_z |
key_b | value_x |
key_c | value_y |
key_d | value_y |
Object keys ordered by frequency
SELECT entry.key, COUNT(*) AS count FROM my_table, json_each_text(my_table.data) AS entry GROUP BY entry.key ORDER BY count DESC;
key | count |
---|
key_a | 4 |
key_b | 1 |
key_c | 1 |
key_d | 1 |
Object values ordered by frequency
SELECT entry.value, COUNT(*) AS count FROM my_table, json_each_text(my_table.data) AS entry GROUP BY entry.value ORDER BY count DESC;
value | count |
---|
value_y | 3 |
value_x | 3 |
value_z | 1 |
Object key-value pairs ordered by frequency
SELECT entry.key, entry.value, COUNT(*) AS count FROM my_table, json_each_text(my_table.data) AS entry GROUP BY entry.key, entry.value ORDER BY count DESC;
key | value | count |
---|
key_a | value_x | 2 |
key_d | value_y | 1 |
key_a | value_y | 1 |
key_b | value_x | 1 |
key_c | value_y | 1 |
key_a | value_z | 1 |