I have data that need to result in JSON format. I am using the following code:
WITH cte AS (
SELECT 'docker' AS type, '564df5a6sdf4654f6da4sf56a' AS id, 1 AS segment, 1 AS value
UNION ALL
SELECT 'docker' AS type, '564df5a6sdf4654f6da4sf56a' AS id, 2 AS segment, 100 AS value
)
SELECT type
, id
, json_agg(json_build_object(segment, value)) AS json_result
FROM cte
GROUP BY type
, id
Result for json_result column is: [{"1" : 1}, {"2" : 100}]
But the desired result is: {"1" : 1, "2" : 100}
How to adjust the query so it returns the desired output?
Use json_object_agg()
:
SELECT type
, id
, json_object_agg(segment, value) AS json_result
FROM cte
GROUP BY type
, id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.