I am trying to output the query to JSON format with multiple arrays, but couldn't make it works correctly. I ran into this link, but it is not quite the output I wanted.
Here are the sample tables:
DECLARE @Persons AS TABLE
(
person_id int primary key,
person_name varchar(20)
)
DECLARE @Pets AS TABLE
(
pet_owner int, -- in real tables, this would be a foreign key to Person.person_id
pet_id int primary key,
pet_name varchar(10)
)
INSERT INTO @Persons (person_id, person_name) VALUES
(2, 'Jack'),
(3, 'Jill')
INSERT INTO @Pets (pet_owner, pet_id, pet_name) VALUES
(2, 4, 'Bug'),
(2, 5, 'Feature'),
(3, 6, 'Fiend')
The JSON output that I want to produce this like this below:
[{
"2" : [{
"pet_id" : 4,
"name" : "Bug",
},
{
"pet_id" : 5,
"name" : "Feature",
}
],
"3" : [{
"pet_id" : 6,
"name" : "Fiend",
}
]
}]
If regular built-in FOR JSON Path
option is not feasible, I also take any tricks like concatenation, etc.