0

My json values in jsonb column are below:

{"Id": "7324326", "UserName":"Henry", "Details": {"Email":"[email protected]", "Phone":"03722", "Images": ["https://face.png"]}}

{"Id": "325325", "UserName":"Mark", "Details": {"Email":"[email protected]", "Phone":"83272", "Images": ["https://hair.png", "https://nose.png"]}}

{"Id": "832743", "UserName":"David", "Details": {"Email":"[email protected]", "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":"[email protected]", "Phone":"03722", "Images": [{"Link":"https://face.png", "UploadedBy":null, "Size":null}]}}

{"Id": "325325", "UserName":"Mark", "Details": {"Email":"[email protected]", "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":"[email protected]", "Phone":"65128", "Images": []}}

1 Answer 1

1

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.

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

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.