0

I have column "elements" in table which is having a json(array json) row values which looks like this

elements
[{"key":12,"value":"qw"},{"key":13,"value":"fa"}]
[{"key":32,"value":"24"},{"key":321,"value":"21"}]

I want to make an column of arrays for every row which consist of keys extracted from that row's json values ,my desired column "result" may look like this

elements result
[{"key":12,"value":"qw"},{"key":13,"value":"fa"}] {12,13}
[{"key":32,"value":"24"},{"key":321,"value":"21"}] {32,321}

is there a way to do it? thank you

2
  • Is the data type of this column really json or does only the data looks like a json, but the data type of this column is varchar or anything else? Commented Apr 20, 2022 at 5:38
  • It was varchar but i converted them to json array Commented Apr 20, 2022 at 5:47

2 Answers 2

2

Schema (PostgreSQL v13)

CREATE TABLE test (
  elements json
);
INSERT INTO test VALUES ('[{"key":12,"value":"qw"},{"key":13,"value":"fa"}]');
INSERT INTO test VALUES ('[{"key":32,"value":"24"},{"key":321,"value":"21"}]');

Query #1

select elements::text, array_agg(cast(value->>'key' as integer)) as result 
from test, json_array_elements(elements)
group by 1
ORDER BY 1;
elements result
[{"key":12,"value":"qw"},{"key":13,"value":"fa"}] 12,13
[{"key":32,"value":"24"},{"key":321,"value":"21"}] 32,321

View on DB Fiddle

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

1 Comment

Well done, thank you. But I think you also should add ORDER BY 1 after the GROUP BY 1
1
select elements::text,
       array_agg(value->>'key') 
from your_table, json_array_elements(elements)
group by 1;

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.