Home > Back-end >  How do convert an array to an object in PostgreSQL with data like this?
How do convert an array to an object in PostgreSQL with data like this?

Time:11-26

[{name:'a',test :1},{name:'b',test :2}]

to

{ a : {test:1}, b:{test:2} }

CodePudding user response:

If your input is valid JSON, you can use the built-in functions and operators and aggregate functions:

SELECT json_object_agg(a.e ->> 'name', a.e - 'name')
FROM jsonb_array_elements('[{"name":"a","test":1},{"name":"b","test":2}]') a(e)

db<>fiddle

  • Related