问题
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"}, ...
回答1:
Like @Abelisto commented, use json_build_object() (or jsonb_build_object()
) to attach a key to your value.
And the simpler json_agg(t) (or jsonb_agg(t)
) instead of array_to_json(array_agg(t))
:
SELECT json_build_object('Locations', json_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;
来源:https://stackoverflow.com/questions/36607635/how-to-add-a-key-to-a-json-array-value