0

Given a row with Col1, Col2. How to convert the row into

[
    {
        "name": "Col1",
        "value": "Column1Value"
    },
    {
        "name": "Col2",
        "value": "Column2Value"
    }
]
`` 

2 Answers 2

2

You can use a scalar subselect:

select (select jsonb_agg(jsonb_build_object('name', key, 'value', value))
        from jsonb_each(to_jsonb(d)) as j)
from the_table d
Sign up to request clarification or add additional context in comments.

Comments

1

Here it is. Substitute the_table with your actual table name.

with jsonrows(jsonobject, rownumber) as 
(
    select to_json(t), row_number() over () 
    from the_table t
)
select json_agg(json_build_object('name', key, 'value', value))
from jsonrows 
cross join lateral json_each_text(jsonobject) 
group by rownumber;

1 Comment

The solution of @a_horse_with_no_name is better I think ...

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.