Working with jsonb
and Postgres I’m running into the following problem:
My output looks like this: [ {columnName: {}}, { columnName: {} } ]
But I would like it to look like this: [ {}, {} ]
I want to put all of the objects in a jsonb
array, but without the column names being added.
Here is the basic query, which can be seen in this fiddle: http://sqlfiddle.com/#!17/b701b8/2
I’ve noticed that when using array_agg()
, the column names are not added, but with JSON they do get added. How to remove the column names so that I can get the desired output using JSON?
select json_agg(v)
from (
select json_build_object('pos',pos, 'type',type, 'color',color)
from (select * from images)a
union all
select json_build_object('pos',pos, 'type',type, 'value',value)
from (select * from letters)b
)v
2
Answers
Aggregate the column instead of the whole row:
Notably, your query produces
json
, notjsonb
.Simpler while nesting whole rows:
Similar for
jsonb
(where whitepace is a non-issue)fiddle
See:
If column types really match between these two tables, you can shorten the query by labelling the rows and building your
jsonb
right where you aggregate: demo at db<>fiddle