How do you use the FOR JSON clause to return query results as JSON?
Posted by JackBrn
Last Updated: July 28, 2024
In SQL Server, the FOR JSON clause is used to format the result set of a query as JSON. It is a straightforward way to convert query results into JSON format, making it easier to send data to applications and web services that consume JSON. Here's a simple guide on how to use the FOR JSON clause:
Basic Usage
1. Single Row Result: If you want to return a single row as a JSON object, you can use the FOR JSON PATH option.
SELECT name, age
   FROM Employees
   WHERE employee_id = 1
   FOR JSON PATH;
This will produce a result like:
[{"name": "John Doe", "age": 30}]
2. Multiple Rows: You can also return multiple rows, and it will create an array of JSON objects.
SELECT name, age
   FROM Employees
   FOR JSON PATH;
This will produce a result like:
[{"name": "John Doe", "age": 30}, {"name": "Jane Smith", "age": 25}]
Customizing the JSON Output
1. Using Aliases: You can customize the keys in the resulting JSON by using aliases.
SELECT name AS EmployeeName, age AS EmployeeAge
   FROM Employees
   FOR JSON PATH;
This will output:
[{"EmployeeName": "John Doe", "EmployeeAge": 30}]
2. Nested JSON: You can create nested JSON by including subqueries with FOR JSON.
SELECT e.name, 
          (SELECT d.department_name 
           FROM Departments d 
           WHERE d.department_id = e.department_id 
           FOR JSON PATH) AS Departments
   FROM Employees e
   FOR JSON PATH;
Other Options
1. Root Property: You can add a root property by using the FOR JSON PATH, ROOT('RootName') option.
SELECT name, age
   FROM Employees
   FOR JSON PATH, ROOT('EmployeesList');
This will produce:
{"EmployeesList":[{"name": "John Doe", "age": 30}, ...]}
2. Including NULLs: By default, NULL values are omitted in the JSON output. You can include those by using INCLUDE_NULL_VALUES.
SELECT name, age, address
   FROM Employees
   FOR JSON PATH, INCLUDE_NULL_VALUES;
Conclusion
The FOR JSON clause is a powerful feature in SQL Server for generating JSON output directly from SQL queries. By using options like PATH, ROOT, and INCLUDE_NULL_VALUES, you can customize the output to fit your application's requirements. This can greatly simplify the process of interfacing with web applications or APIs that require JSON.
Related Content