2

In my database, I have a column that stores an array of elements, g.e, {"B", "A", "C"}. And I am trying to firstly sort this array alphabetically and then create a JSON from each element in the sorted array and then return it like the following:

{TEXTS : [{"TEXT":"A","sortOrder":1}, {"TEXT":"B","sortOrder":2}, {"TEXT":"C","sortOrder":3}]}

How can I achieve this?

2
  • 1
    The part {texts = ...} isn't valid JSON. If that is the intended output, then please also show us the input this is based on. Commented Mar 18, 2021 at 11:48
  • You are right, I edited the output Commented Mar 18, 2021 at 11:52

1 Answer 1

1

The algorythm is simple:

  1. Decompose array to row set
  2. Sort row set
  3. Aggregate row set into JSON object
select json_build_object('TEXTS', json_agg(t.*))
from (
    select "TEXT", row_number() over (order by "TEXT") as "sortOrder"
    from unnest('{B,A,C}'::text[]) as "TEXT") as t;

demo

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.