Using sub queries to create JSON file

746 views Asked by At

I'm trying to create a JSON file for a new project that I'm currently looking into I've got most of it working as expected but I'm now at a point where I'm trying to use sub queries in order to format the JSON correctly.

I've tried to use the following sub query but SQL doesn't like the formatting.

` SELECT

'Admin User TEST ONLY PLEASE IGNORE' AS AdditionalNotes


(
   SELECT v.atFault 
   FROM dbo.ic_DP_AX ax
   CROSS APPLY (VALUES (ax.Acc_fault1), (ax.Acc_fault2)) v (atFault)
   FOR JSON AUTO
   ) AS InsuredPartyClaims,
   (
   SELECT Acc_fault3 AS atFault 
   FROM dbo.ic_DP_AX
   FOR JSON AUTO
   ) AS InsuredPartyConvictions
FOR JSON PATH) ROOT('InsuredParties')



FROM

    dbo.icp_Daprospect AS p INNER JOIN
    dbo.icp_Dapolicy AS d ON p.Branch@ = d.Branch@ AND p.ClientRef@ = 
 d.ClientRef@ LEFT OUTER JOIN
    dbo.ic_DP_AX AS  ax ON P.Branch@ = ax.B@ AND ax.PolRef@ = d.PolicyRef@ 
LEFT OUTER JOIN
WHERE 
    d.PolicyRef@ = '' AND
    d.Branch@ = 0`

FOR JSON PATH

The output I'm trying to achieve is:

"InsuredParties": [
    {
        "InsuredPartyClaims": [
            {
                "atFault": false
            },
            {
                "atFault": true
            }
        ],
        "InsuredPartyConvictions": [ 
           {
                "atFault": false
           },
           

Can anyone see what I'm doing wrong? I'm trying to keep this as simple as possible.

2

There are 2 answers

1
SteveC On

The subqueries need to return JSON as well.

Try

(
  (SELECT ax.Acc_fault1 AS [atFault] FROM dbo.ic_DP_AX AS ax FOR JSON PATH) AS [PartyClaims]
  (SELECT ax.Acc_fault2 AS [atFault] FROM dbo.ic_DP_AX AS ax FOR JSON PATH) AS [PartyClaims]
  (SELECT ax.Acc_fault3 AS [atFault] FROM dbo.ic_DP_AX AS ax FOR JSON PATH) AS [PartyConvictions]
) FOR JSON PATH AS [InsuredParties]
3
Zhorov On

It's always difficult without sample data, but the foolowing example is a possible solution:

Table:

CREATE TABLE dbo.ic_DP_AX (Acc_fault1 bit, Acc_fault2 bit, Acc_fault3 bit)
INSERT INTO dbo.ic_DP_AX (Acc_fault1, Acc_fault2, Acc_fault3)
VALUES (0, 1, 0)

Statment:

SELECT
   (
   SELECT v.atFault 
   FROM dbo.ic_DP_AX ax
   CROSS APPLY (VALUES (ax.Acc_fault1), (ax.Acc_fault2)) v (atFault)
   FOR JSON AUTO
   ) AS InsuredPartyClaims,
   (
   SELECT Acc_fault3 AS atFault 
   FROM dbo.ic_DP_AX
   FOR JSON AUTO
   ) AS InsuredPartyConvictions
FOR JSON PATH, ROOT('InsuredParties')   

Result:

{
  "InsuredParties":[
    {
      "InsuredPartyClaims":[
        {
          "atFault":false
        },
        {
          "atFault":true
        }
      ],
      "InsuredPartyConvictions":[
        {
          "atFault":false
        }
      ]
    }
  ]
}