I am new to Postgres and using version 9.4. I have a query returning a json
column.
How can I add a key to a JSON array value?
My query:
select array_to_json(array_agg(t))
from (select DISTINCT ON(city,state)latitudes,longitudes,city,state
from zips where city ilike 'ORL%'
order by city,state,ziptype desc
limit 10) t;
The output is like:
[{"latitudes": 31.22,"longitudes": -103.91,"city": "Orla","state": "TX"}, ...
However, I would like to name it such as:
["Locations": [{"latitudes": 31.22,"longitudes": -103.91,"city": "Orla","state": "TX"}, ...
Like @Abelisto commented, use
json_build_object()
(orjsonb_build_object()
) to attach a key to your value.And the simpler
json_agg(t)
(orjsonb_agg(t)
) instead ofarray_to_json(array_agg(t))
: