1

I need a SQL query where I can select all json keys. The following query let's me get all the keys to the JSON field. But I'm a bit at loss how I would go about making a query to also get all the values out too.

SELECT DISTINCT ON (key.*) key.*
FROM my_table,
jsonb_object_keys(my_table.json_field) as key

So the result of the above query would simply just be

key1 
key2

With the following query you would get a result similar to this

SELECT * FROM my_table

| id | json_field |
| -- | ---------- |
| 1  | '{"key1": "value1"}' |
| 2  | '{"key2": "value2"}' |

The result I'm looking for would be the following

| id | key1   | key2   |
| -- | -------| ------ | 
| 1  | value1 | null   |
| 2  | null   | value2 |

What makes it difficult is that I don't know the names of all keys which also may be a lot of keys for a single row.

Jonathan
  • 8,453
  • 9
  • 51
  • 74

1 Answers1

1
select distinct on (field_1, field_2) id, job_id, field_1, field_2
from
    my_table,
    jsonb_populate_recordset(json_field) jprs (field_1 int, field2 text)

https://www.postgresql.org/docs/current/static/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE

Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260