Skip to content
Advertisement

How to append nested key-value to json array in postgresql?

My json values in jsonb column are below:

{"Id": "7324326", "UserName":"Henry", "Details": {"Email":"henry@test.com", "Phone":"03722", "Images": ["https://face.png"]}}

{"Id": "325325", "UserName":"Mark", "Details": {"Email":"mark@test.com", "Phone":"83272", "Images": ["https://hair.png", "https://nose.png"]}}

{"Id": "832743", "UserName":"David", "Details": {"Email":"david@test.com", "Phone":"65128", "Images": []}}

I have nested key – "Images" that has array of strings. How to write query that will add to Images new keys/values ("UploadedBy":null and "Size":null) and transform array of string to key-value ("https://face.png" -> "Link":"https://face.png") like below:

{"Id": "7324326", "UserName":"Henry", "Details": {"Email":"henry@test.com", "Phone":"03722", "Images": [{"Link":"https://face.png", "UploadedBy":null, "Size":null}]}}

{"Id": "325325", "UserName":"Mark", "Details": {"Email":"mark@test.com", "Phone":"83272", "Images": [{"Link":"https://hair.png", "UploadedBy":null, "Size":null}, {"Link":"https://nose.png", "UploadedBy":null, "Size":null}]}}

{"Id": "832743", "UserName":"David", "Details": {"Email":"david@test.com", "Phone":"65128", "Images": []}}

Advertisement

Answer

You can use jsonb_set:

update tbl set js = jsonb_set(js, '{Details,Images}'::text[], 
    coalesce((select jsonb_agg(jsonb_build_object('Link', v.value, 'UploadedBy', null, 'Size', null)) 
     from jsonb_array_elements(js -> 'Details' -> 'Images') v), '[]'::jsonb))

See fiddle.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement