We are trying to use FOR JSON Path in SQL Server 2016 for forming a Nested Array from a SQL Query.
SQL Query:
SELECT A,
B.name as [child.name],
B.date as [child.date]
from Table 1 join Table 2 on Table 1.ID=Table 2.ID FOR JSON PATH
Desired Output:
[{
A:"text",
"child:"[
{"name":"value", "date":"value"},
{"name":"value", "date":"value"}
]
}]
However what we are getting is:
[{
A:"text",
"child:" {"name":"value", "date":"value"}
},
{
A:"text",
"child":{"name":"value", "date":"value"}
}]
How can we use FOR JSON PATH to form nested child array.
instead of join use nested query, e.g.:
SELECT A
, child=(
SELECT B.name as [child.name]
, B.date as [child.date]
FROM Table 2
WHERE Table 2.ID = Table 1.ID
FOR JSON PATH
)
from Table 1 FOR JSON PATH
(the query in the question is broken af so this query is just as broken but should give you the idea)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With