2

I'm running PostgreSQL and are trying to convert this:

SELECT car_id AS id, car_model AS model FROM cars

into this:

[{ "id" : 123, "model" : "Fiat" }, {"id": 124, "model": "BMW"}, ...]

I've tried:

SELECT json_agg(
           json_build_object(car_id AS id),
           json_build_object(car_model AS model)
       ) FROM cars

and a lot other stuff, but seems to be stuck

1 Answer 1

2

You can try to use only one json_build_object in json_agg function.

json_build_object explain from the document.

Builds a JSON object out of a variadic argument list. By convention, the argument list consists of alternating keys and values.

using json_build_object function parameter will be like

json_build_object([key1],[Key_Value1],[key2],[Key_Value2]..)

TestDLL

CREATE TABLE cars(
   car_id INT,
   Car_Model VARCHAR(50)
);

INSERT INTO cars VALUES (1,'TEST1');
INSERT INTO cars VALUES (2,'TEST2');

Query

SELECT json_agg(json_build_object('ID', car_id , 'Model', car_model ))
from cars

Result

|                                                         result |
|----------------------------------------------------------------|
| [{"ID" : 1, "Model" : "TEST1"}, {"ID" : 2, "Model" : "TEST2"}] |

sqlfiddle

1
  • Thank you. :) Works, sometimes it's easier than expected. Commented Aug 3, 2018 at 8:14

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.