How to add root node to JSON output in MSSQL?

MSSQL 2016 has a new feature where you can return the data as JSON output format and also add root node to JSON output in MSSQL. Checkout MSSQL Built-In JSON support for more details.

The FOR JSON returns the JSON data when it is used with the select query, however, the JSON data will not have the root node.

SELECT name, surname
FROM emp
FOR JSON AUTO

Output in JSON format

[ 
   { "name": "John" },
   { "name": "Jane", "surname": "Doe" }
]

As we saw in the earlier example the JSON output does not have the root node. Now in this example lets see how to return the data output with root node using MSSQL query.

SQL Query to add root node to JSON output in MSSQL

SELECT name, surname
FROM emp
FOR JSON AUTO, ROOT('info')

Output in JSON format with ROOT node as info

{ "info": [ 
     { "name": "John", "surname": "Doe" },
     { "name": "Jane", "surname": "Doe" }
   ]
}
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like