How to add a key to a JSON array value?

别来无恙 提交于 2019-12-13 02:42:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!