Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i convert each row from resultset to a json and then add them to a single array in postgresql

I have three tables

Owner
-----------------------
id         | long
name       | string
Animal
-----------------------
id         | long
status     | string
external_d | string
region     | long (fk to region table)
owner_id    | long (fk to owner table)
Region
-----------------------
id         | long
name       | string

I want to get multiple rows from the Animal table. Each record should contain the id, status, externalId and region.

Each row should be a JSON object and all the results should be in an array. e.g

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
   {id: 3, status: 'alive', externalId: 'abc90', regionId: 2},
   {id: 9, status: 'dead', externalId: 'xuy12', regionId: 2},
   {id: 13, status: 'alive', externalId: 'ter34', regionId: 2}
]

I have tried to make the query as follows.

SELECT JSON_ARRAY(
    JSON_OBJECT(
        'id', id, 
        'externalId', externalId, 
        'status', status, 
        'regionId', regionId
        )
    ) as final_data
    FROM 
    (SELECT 
        a.id as id, 
        a.external_id as externalId, 
        a.status as status, 
        a.region_id as regionId 
    FROM 
        myDB.animal a 
    WHERE a.owner_id=12) as data;

running the above query gives me all the required columns in JSON format but each row is an array instead of all JSON objects in a single array.

Can someone help me solve this.

>Solution :

You can use json_arrayagg() to return all JSON objects in a single array :

SELECT JSON_ARRAYAGG(
          JSON_OBJECT(
            'id', id, 
            'externalId', external_id, 
            'status', status, 
            'regionId', region_id
          )
       ) as final_data
FROM animal
WHERE owner_id=12;

Demo here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading