0

I have a table t with 2 fields: one containing an id, and the other one containing a json.
My table looks like this:
| id | json                                          | 
|:---|:----------------------------------------------|
| 1  | {"tag1":45, "tag2": 3, "tag5": 10}            |
| 2  | {"tag5":35, "tag6": 7, "tag8": 10, "tag10": 4}|
| 3  | {"tag2":10, "tag800": 6}                      |

I am trying to write a postgresql query to create a table that looks like the following but I am stuck:

| id |   key   | Value |
|:---|:--------|:------|
| 1  | tag1    | 45    |
| 1  | tag2    | 3     |
| 1  | tag5    | 10    |
| 2  | tag5    | 35    |
| 2  | tag6    | 7     |
| 2  | tag8    | 10    |
| 2  | tag10   | 4     |
| 3  | tag2    | 10    |
| 3  | tag800  | 6     |

Note that there are thousands of different keys in my data.
Any help would be much appreciated. Thanks!

1
  • You are looking for jsonb_each() Commented Feb 18, 2022 at 14:38

1 Answer 1

1

Recreating your example with

CREATE TABLE test(id int, mydata jsonb);

insert into test values (1, '{"tag1":45, "tag2": 3, "tag5": 10}');
insert into test values (2, '{"tag5":35, "tag6": 7, "tag8": 10, "tag10": 4}');
insert into test values (3, '{"tag2":10, "tag800": 6} ');

You can achieve what you're looking for with the jsonb_each function

select id, key, value from test, jsonb_each(test.mydata) 
Sign up to request clarification or add additional context in comments.

Comments

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.