Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server FOR JSON Path Nested Array

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.

like image 846
code_blue Avatar asked Aug 18 '17 00:08

code_blue


Video Answer


1 Answers

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)

like image 154
gordy Avatar answered Oct 10 '22 11:10

gordy