skip to Main Content

I am using below code to generate JSON, but I cannot seem to find a way to add an extra "root" to the JSON.
I have tried to add multiple "roots" by using subqueries, but it does not work as it puts the "connection" root under the other.

SELECT 
       [cola] as [source.name]
      ,[colb] as [destination.name] 
FROM [db].[dbo].[table]
FOR JSON PATH, ROOT('connection')

It returns below JSON:

{
  "connection": [
    {
      "source": {
        "name": "val1"
      },
      "destination": {
        "name": "val2"
      }
    },
    {
      "source": {
        "name": "val3"
      },
      "destionation": {
        "name": "val"
      }
    }
  ]
}

But I want to return:

{
  "type": "iwantthistobeincluded",
  "connection": [
    {
      "source": {
        "name": "val1"
      },
      "destination": {
        "name": "val2"
      }
    },
    {
      "source": {
        "name": "val3"
      },
      "destination": {
        "name": "val4"
      }
    }
  ]
}

2

Answers


  1. Just wrap it in another select?

    select "iwantthistobeincluded" AS type
    , (
    SELECT 
           [cola] as [source.name]
          ,[colb] as [destination.name] 
    FROM [db].[dbo].[table]
    FOR JSON PATH
    ) as connection
    for json path
    
    Login or Signup to reply.
  2. you can add tag type in First Tage

    SELECT 
           [cola] as [source.name]
          ,[colb] as [destination.name] 
    FROM #Test
    FOR JSON PATH, ROOT('type: iwantthistobeincluded,connection')
    
    

    You can insert Example Data with the following codes

    create table #Test(cola varchar(100),colb varchar(100))
    insert into #Test
    (cola,colb)
    select 'val1','val2'
    union select 'val3','val4'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search