I have been trying to create a json object in sql from three tables
The main table/entity is "order" that have a id as addressId
and further address table has countryId and stateId which refers to
state table and country table
orderTable
Id AddressId Status
1 1 Processed
AddressTable
Id countryId stateId FirstName LastName
1 5 7 John cena
countryTable
Id Name
5 usa
StateTable
Id Name
7 DC
The output should show as below
{
"firstName": "John",
"lastName": "cena",
"Country" : {
"name": "usa",
"id" : "5"
},
"States" : {
"name": "DC",
"id" : "7"
}
}
I have tried using this query and get similar results but I want to remove [] [] array object containers from json
[ // I want to remove this
{
"FirstName": "Steve",
"LastName": "Gates",
"country":
[ // I want to remove this
{
"name": "usa",
"id" : "5"
}
], // I want to remove this
"states" :
[ // I want to remove this
{
"name": "DC",
"id" : "7"
}
] // I want to remove this
As per microsoft's blog we can use
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
but if I use this , then it does not include country and state as separate child objects so I have used "FOR JSON AUTO" which gives me desired output but it additionally adds square bractes to each json object
This is my query
Select ord.*, (Select * from Address ad Left outer join Country country on country.Id = ad.CountryId
Left outer join State sp on sp.Id = ad.StateId where ad.Id = ord.AddressId FOR JSON AUTO) as AddressJson
, (Select * from Address ad Left outer join Country country on country.Id = ad.CountryId
Left outer join State sp on sp.Id = ad.StateId where ad.Id = ord.AddressId1 FOR JSON AUTO, WITHOUT_ARRAY_WRAPPER) as AddressJson2
from [order] ord )