Mj Ebrahimzadeh
Mj Ebrahimzadeh

Reputation: 647

How to get Array of JSON from SQL select

I want to get an array of objects inside of my SQL select.

SELECT id, a.name antibodyName, c.name colorName, c.location colorLocation 
FROM Antibodies a 
JOIN AssignedColors c ON id = antiId 
WHERE colorId IS NOT NULL

and I get this response:

[
  { id: 1, antibodyName: 'antibody 1', colorName: 'red', colorLocation: 'A5/C3' },
  { id: 2, antibodyName: 'antibody 2', colorName: 'red', colorLocation: 'C3/A1' },
  { id: 2, antibodyName: 'antibody 2', colorName: 'yellow', colorLocation: 'E4/F2' }
]

is it possible to get something like this?

[
  { id: 1, antibodyName: 'antibody 1', colors: [{name: 'red, location: 'A5/C3'}] },
  { id: 2, antibodyName: 'antibody 2', colors: [{name: 'red, location: 'C3/A1'}, {name: 'yellow', location: 'E4/F2'}] },
]

Upvotes: 0

Views: 653

Answers (2)

Muhammad Ahmod
Muhammad Ahmod

Reputation: 709

a bit rusty, but try this:

SELECT
a.id AS 'Id',
a.Name AS 'antibodyName',
c.Name AS 'name',
c.location AS 'location'
FROM Antibodies a
LEFT JOIN AssignedColors c ON c.id = a.Id
FOR JSON AUTO;

UPDATE: the above is not for SQLite. For SQLite you should checkout the json1 extension here: https://www.sqlite.org/json1.html

ANOTHER UPDATE: it can be done without the JSON extention...

SELECT
a.id AS 'id',
a.Name AS 'antibodyName',
(SELECT '[' || GROUP_CONCAT('{name:"' || Name || '", location:"' || location || '"}') ||']'
 FROM AssignedColors
 WHERE c.id=Id) AS colors
 FROM Antibodies a
 LEFT JOIN AssignedColors c ON c.id = a.id
 GROUP BY a.id

theres a small issue here: the colors column/node is treated as a string and not an array... this is normal as sqlite doesnt support a column of type array. some parsing will need to be done to convert from string to array...

Upvotes: 1

sheharbano
sheharbano

Reputation: 219

Use json_build_object and array_agg.

WITH foobar AS ( 
    SELECT id, a.name antibodyName, c.name colorName, c.location colorLocation 
    FROM Antibodies a JOIN AssignedColors c
    ON id = antiId WHERE colorId IS NOT NULL
    )
SELECT 
     json_build_object('data',array_agg(json_build_object('id', id, 'antibodyName', antibodyName, 'colorName', colorName, 'colorLocation', colorLocation))
FROM 
    foobar

Upvotes: 1

Related Questions