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.

4
  • Please show your schema structure and sample input/output. Or at best dbfiddle.uk demo. Commented Aug 1, 2017 at 8:12
  • I made an update that clarifies the structure better. Commented Aug 1, 2017 at 9:00
  • Flatten aggregated key/value pairs from a JSONB field? Commented Aug 1, 2017 at 9:12
  • @klin That looks like what I'm looking for! Commented Aug 1, 2017 at 9:18

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I amended the question to better explain what I was after.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.