T-SQL Tutorial

SQL Server JSON_OBJECT


The JSON_OBJECT function in SQL Server is used to create a JSON object from a set of key-value pairs. It is a built-in function that was introduced in SQL Server 2022 and is available in SQL Server 2022. You can use JSON_OBJECT to create JSON documents from relational data stored in SQL Server. You can also use JSON_OBJECT in combination with other JSON functions in SQL Server, such as JSON_ARRAY or JSON_QUERY, to create complex JSON documents.


Syntax

The syntax of the JSON_OBJECT function is as follows:

JSON_OBJECT (key1, value1, [key2, value2, ...])

The function takes a set of key-value pairs as input parameters, where the key is a string that represents the name of a property in the resulting JSON object, and the value is an expression that represents the value of the corresponding property in the resulting JSON object.


Example

For example, consider the following query:

SELECT JSON_OBJECT('name', 'John', 'age', 30) AS person;

The above query would return a JSON object that looks like this:

{
"name": "John",
"age": 30
}

In the example above, we passed two key-value pairs to the JSON_OBJECT function. The first key-value pair represents the "name" property in the resulting JSON object, and its value is the string "John". The second key-value pair represents the "age" property in the resulting JSON object, and its value is the integer 30.

Note that you can also use expressions as the key or the value in the key-value pairs. For example:

SELECT JSON_OBJECT(1 + 1, 'John', 'age', 30 * 2) AS person;

The above query would return a JSON object that looks like this:

{
"2": "John",
"age": 60
}

In this example, we used an expression "1 + 1" as the key for the first key-value pair, which evaluates to the integer 2. We also used an expression "30 * 2" as the value for the second key-value pair, which evaluates to the integer 60.

In conclusion, the JSON_OBJECT function in SQL Server provides a convenient way to create JSON objects from a set of key-value pairs. It is useful for tasks such as creating JSON output for web services or processing JSON data in SQL Server.