1

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"}, ...
2
  • 2
    json_build_object('Locations', array_to_json(array_agg(t))) Commented Apr 13, 2016 at 19:41
  • Thanks a lot that worked Commented Apr 13, 2016 at 19:51

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

BTW It seems that PostgreSQL 9.4 (mentioned in the Q tags) does not provides some functions for the jsonb type unlike the 9.5 version.
@Abelisto: Yes, jsonb_agg() is new in Postgres 9.5. You can substitute with json_agg(t)::jsonb in pg 9.4. Either way, the presented query works for pg 9.4 (the OP requested json, not jsonb).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.