5

I am attempting to build a JSON object with a postgres query. The output I'm looking for is similar to the object below. The properties "xxx" and "yyy" come from a column as do the dates.

{
    "xxx": [ "2018-07-26T11:42:04.514Z", "2018-07-26T11:52:04.514Z"],
    "yyy": [ "2018-07-26T05:42:09.210Z", "2018-07-26T07:22:04.024Z"]
}

I was hoping to do this with a query similar to the one below:

SELECT
    json_object(
        array_agg(name),
        array_agg(json_build_array(start_date, end_date)
    )
FROM my_table

The my_table table would look roughly like this:

name | start_date                | end_date                 |
-------------------------------------------------------------
xxx  | 2018-07-26T11:42:04.514Z  | 2018-07-26T11:52:04.514Z |
yyy  | 2018-07-26T05:42:09.210Z  | 2018-07-26T07:22:04.024Z |

However, json_object only accepts text arrays and I can't seem to find an alternative. So, I get ERROR: function json_object(text[], json[]) does not exist. Thanks for reading!

1 Answer 1

10

Use jsonb_build_array() and json_object_agg().

select json_object_agg(name, jsonb_build_array(start_date, end_date))
from my_table

DbFiddle.

Sign up to request clarification or add additional context in comments.

Comments

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.