0

Input:

[{"name": "X", "strength": "10"}, {"name": "Y", "strength": "30"}]

Desired output:

X-Y 10-30

1 Answer 1

1

First aggregate into arrays and then convert the arrays to strings.

select array_to_string(array_agg(j ->> 'name'), ','), 
       array_to_string(array_agg(j ->> 'strength'), ',') 
from jsonb_array_elements
('[
   {"name": "X", "strength": "10"}, 
   {"name": "Y", "strength": "30"},
   {"name": "Z", "strength": "20"}
]') j;

When doing on a table column:

select col1,
       (select array_to_string(array_agg(j ->> 'name'), ',')
        from json_array_elements(cast(col1 as json)) j),
    (select array_to_string(array_agg(j ->> 'strength'), ',')
        from json_array_elements(cast(col1 as json)) j)
from table1;
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.