Search code examples
jsonpostgresqljsonb

Return a json of multiple key-value pairs instead of list of single-paired key-value jsons


Currently my query looks like follows and returns the results below:

select
    c.id as company_id,
    json_agg(json_build_object(ds.statement_ref, value)) as financials
from
    st.data_statements ds
    join st.company_data cd on ds.company_datum_id = cd.id
    join st.companies c on cd.company_id = c.id
where
    c.id = 61
group by
    c.id

The result looks like this:

61  [{"in31" : "0.0"}, {"in32" : "145.8"}, {"in34" : "134.0"}]

How do I modify the query above to return all key pair values within the same JSON object (rather then a list of jsons)? Expected output:

61  {"in31" : "0.0", "in32" : "145.8", "in34" : "134.0"}

Solution

  • Replace

    json_agg(json_build_object(ds.statement_ref, value)) as financials
    

    with

    json_object_agg(ds.statement_ref, value) as financials