FOR JSON Statement

You can execute a SQL query against your database and return the results as a JSON document by using the FOR JSON clause in a SELECT statement.

JavaScript Object Notation (JSON) is a language-independent, text-based data interchange format developed for the serialization of JavaScript data. JSON also represents two structured types: objects and arrays. For more details about JSON format, see http://www.json.org

Syntax

...For JSON mode
mode :
RAW | AUTO | EXPLICIT

Parameters

The mode controls the format of the JSON that is generated:
  • RAW – returns query results as a flattened JSON representation. Although this mode is more verbose, it can be easier to parse.
  • AUTO – returns query results as nested JSON objects, based on query joins.
  • EXPLICIT – allows you to specify how column data is represented. You can specify columns as simple values, objects, or nested objects to produce uniform or heterogeneous arrays.

Examples

Usage

The FOR JSON clause can be used in any SELECT statement, including subqueries, queries with a GROUP BY clause or aggregate functions, and view definitions. Using the FOR JSON clause represents relational data as a JSON array composed of arrays, objects, and scalar elements.

The RAWclause is the recommended method for retrieving query results as JSON objects as it is the easiest method to parse and understand.

Use the AUTO clause in a query when you want the result set to show the hierarchical relationship between the JSON objects.

The EXPLICIT clause uses a column alias to provide a detailed format specification. If an alias is not present, then the given column is output as a value. An alias must be present to express a value (or object) within a nested structure. You must name the first two columns in the select-list tag and parent. A union of multiple queries can return nested JSON output by specifying the tag and parent relationship within each query.

The format for the alias directive is
[encapsulating_object!tag!name!qualifier]
where:

Standards

ANSI SQL – Compliance level: Transact-SQL extension.

Permissions

None