Table public.challenge, column lines JSONB
My initial JSON in lines :
[
{
"line": 1,
"blocs": [
{
"size": 100,
"name": "abc"
},
{
"size": 100,
"name": "def"
},
{
"size": 100,
"name": "ghi"
}
]
},
{
"line": 2,
"blocs": [
{
"size": 100,
"name": "xyz"
}
]
}
]
Desired result (add a new object wrapper for every bloc) :
[
{
"line": 1,
"blocs": [
{
"size": 100,
"name": "abc",
"wrapper": {
"nestedName": "abc",
"type": "regular"
}
},
{
"size": 100,
"name": "def",
"wrapper": {
"nestedName": "def",
"type": "regular"
}
},
{
"size": 100,
"name": "ghi",
"wrapper": {
"nestedName": "ghi",
"type": "regular"
}
}
]
},
{
"line": 2,
"blocs": [
{
"size": 100,
"name": "xyz",
"wrapper": {
"nestedName": "xyz",
"type": "regular"
}
}
]
}
]
I have the following query (from here) :
WITH cte AS (
SELECT id_lines,
jsonb_agg(
jsonb_set(val1, '{blocs}',
(
SELECT jsonb_agg(arr2 ||
json_build_object(
'wrapper', json_build_object('nestedName', arr2->'name', 'type', 'regular')
)::jsonb
)
FROM jsonb_array_elements(arr1.val1->'blocs') arr2
WHERE arr2->'name' IS NOT NULL
)
))
FROM public.challenge, jsonb_array_elements(lines) arr1(val1)
GROUP BY 1
)
UPDATE public.challenge SET lines=(cte.jsonb_agg) FROM cte
WHERE public.challenge.id_lines=cte.id_lines;
The condition WHERE arr2->'name' IS NOT NULL does not filter out blocs where name is null, I struggle to find out why.. thanks!