简体   繁体   中英

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": []}}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM