Have a table with json column, this json is quite big, so I want to filter/select only speicific nested keys.
Json Example:
{
"title":{
"nested_1":"This is nested key 1",
"nested_2":"This is nested key 2",
"nested_3":"This is nested key 3",
"nested_4":"This is nested key 4",
"nested_5":"This is nested key 5"
},
"description":{
"nested_1":"This is nested key 1",
"nested_2":"This is nested key 2",
"nested_3":"This is nested key 3",
"nested_4":"This is nested key 4",
"nested_5":"This is nested key 5"
},
"meta":{
"nested_1":"This is nested key 1",
"nested_2":"This is nested key 2",
"nested_3":"This is nested key 3",
"nested_4":"This is nested key 4",
"nested_5":"This is nested key 5"
}
}
In example I want to select only nested_3 and nested_5 (But keep the json structure):
{
"title":{
"nested_3":"This is nested key 3",
"nested_5":"This is nested key 5"
},
"description":{
"nested_3":"This is nested key 3",
"nested_5":"This is nested key 5"
},
"meta":{
"nested_3":"This is nested key 3",
"nested_5":"This is nested key 5"
}
}
What I tried so far:
select
id,
(select json_object_agg(key, val) from (
values
('nested_3', (select json_object_agg(t.token, t.content->'nested_3') from json_each(json_col) as t(token, content))),
('nested_5', (select json_object_agg(t.token, t.content->'nested_5') from json_each(json_col) as t(token, content)))
) as foo(key, val)) as json_col
from my_table
This is working but gives the opposite result (logical, based on above query):
{
"nested_3": {
"title": "This is nested key 3",
"description": "This is nested key 3",
"meta": "This is nested key 3"
},
"nested_5": {
"title": "This is nested key 5",
"description": "This is nested key 5",
"meta": "This is nested key 5"
}
}
I've also tried to nest:
(select json_object_agg(t.token, json_object_agg(t.content->'nested_3', t.languages->'nested_5')) from json_each(json_col) as t(token, content))
But this gives me an error: aggregate function calls cannot be nested
There is a way to select only specific nested keys but preserve the json structure?
Postgres version: 12