3

I have an array of strings, like this:

SELECT ARRAY['[email protected]', '[email protected]', '[email protected]'];

How do I convert (map?) it into a jsonb array of jsonb objects like this?:

SELECT [{"email": "[email protected]"}, {"email": "[email protected]"}, {"email": "[email protected]"}]::jsonb;

1 Answer 1

4

demo:db<>fiddle

SELECT
    jsonb_agg(jsonb_build_object('email', elems))
FROM (
    SELECT ARRAY['[email protected]', '[email protected]', '[email protected]'] AS a
) s,
unnest(a) AS elems
  1. Expand the array elements into one record each with unnest()
  2. Create the JSON objects using jsonb_object_build() to create the key/value structure your are expecting
  3. re-aggregate these objects into one new JSON array using jsonb_agg()
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.