Skip to content

Commit 90bf03e

Browse files
committed
FOR JSON: Fix images and refresh article
1 parent abefc8f commit 90bf03e

6 files changed

Lines changed: 116 additions & 139 deletions

File tree

Lines changed: 116 additions & 139 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
11
---
2-
description: "Format Query Results as JSON with FOR JSON (SQL Server)"
32
title: "Format Query Results as JSON with FOR JSON"
4-
ms.date: 10/21/2021
3+
description: "Format Query Results as JSON with FOR JSON (SQL Server)"
4+
author: jovanpop-msft
5+
ms.author: jovanpop
6+
ms.reviewer: jroth, randolphwest
7+
ms.date: 08/09/2022
58
ms.prod: sql
6-
ms.technology:
79
ms.topic: conceptual
8-
helpviewer_keywords:
10+
ms.custom:
11+
- seo-dt-2019
12+
- FY22Q2Fresh
13+
helpviewer_keywords:
914
- "FOR JSON"
1015
- "JSON, exporting"
1116
- "exporting JSON"
12-
author: jovanpop-msft
13-
ms.author: jovanpop
14-
ms.reviewer: jroth
15-
ms.custom: seo-dt-2019, FY22Q2Fresh
1617
monikerRange: "=azuresqldb-current||>=sql-server-2016||>=sql-server-linux-2017||=azuresqldb-mi-current"
1718
---
1819
# Format Query Results as JSON with FOR JSON (SQL Server)
@@ -21,48 +22,50 @@ monikerRange: "=azuresqldb-current||>=sql-server-2016||>=sql-server-linux-2017||
2122

2223
Format query results as JSON, or export data from SQL Server as JSON, by adding the `FOR JSON` clause to a `SELECT` statement. Use the `FOR JSON` clause to simplify client applications by delegating the formatting of JSON output from the app to [!INCLUDE[ssNoVersion](../../includes/ssnoversion-md.md)].
2324

24-
> [!NOTE]
25+
> [!NOTE]
2526
> [Azure Data Studio](../../azure-data-studio/download-azure-data-studio.md) is the recommended query editor for JSON queries because it auto-formats the JSON results (as seen in this article) instead of displaying a flat string.
26-
27-
When you use the `FOR JSON` clause, you can specify the structure of the JSON output explicitly, or let the structure of the SELECT statement determine the output.
28-
29-
- To maintain full control over the format of the JSON output, use `FOR JSON PATH`. You can create wrapper objects and nest complex properties.
30-
31-
- To format the JSON output automatically based on the structure of the SELECT statement, use `FOR JSON AUTO`.
32-
27+
28+
When you use the `FOR JSON` clause, you can specify the structure of the JSON output explicitly, or let the structure of the SELECT statement determine the output.
29+
30+
- To maintain full control over the format of the JSON output, use `FOR JSON PATH`. You can create wrapper objects and nest complex properties.
31+
32+
- To format the JSON output automatically based on the structure of the SELECT statement, use `FOR JSON AUTO`.
33+
3334
Here's an example of a **SELECT** statement with the `FOR JSON` clause and its output.
34-
35-
:::image type="content" source="../../relational-databases/json/media/jsonslides2forjson.png" alt-text="FOR JSON" lightbox="../../relational-databases/json/media/jsonslides2forjson.png":::
3635

37-
36+
:::image type="content" source="media/format-query-results-as-json-with-for-json-sql-server/for-json.png" alt-text="Diagram showing how FOR JSON works." lightbox="media/format-query-results-as-json-with-for-json-sql-server/for-json.png":::
37+
3838
## Option 1 - You control output with FOR JSON PATH
39-
In **PATH** mode, you can use the dot syntax - for example, `'Item.UnitPrice'` - to format nested output.
4039

41-
Here's a sample query that uses **PATH** mode with the `FOR JSON` clause. The following example also uses the **ROOT** option to specify a named root element.
42-
43-
:::image type="content" source="../../relational-databases/json/media/forjson-example1.png" alt-text="Diagram of flow of FOR JSON output" lightbox="../../relational-databases/json/media/forjson-example1.png":::
40+
In **PATH** mode, you can use the dot syntax - for example, `'Item.Price'` - to format nested output.
41+
42+
Here's a sample query that uses **PATH** mode with the `FOR JSON` clause. The following example also uses the **ROOT** option to specify a named root element.
43+
44+
:::image type="content" source="media/format-query-results-as-json-with-for-json-sql-server/for-json-path.png" alt-text="Diagram of flow of FOR JSON output." lightbox="media/format-query-results-as-json-with-for-json-sql-server/for-json-path.png":::
4445

4546
### More info about FOR JSON PATH
47+
4648
For more detailed info and examples, see [Format Nested JSON Output with PATH Mode (SQL Server)](../../relational-databases/json/format-nested-json-output-with-path-mode-sql-server.md).
4749

48-
For syntax and usage, see [FOR Clause (Transact-SQL)](../../t-sql/queries/select-for-clause-transact-sql.md).
50+
For syntax and usage, see [FOR Clause (Transact-SQL)](../../t-sql/queries/select-for-clause-transact-sql.md).
4951

5052
## Option 2 - SELECT statement controls output with FOR JSON AUTO
53+
5154
In **AUTO** mode, the structure of the SELECT statement determines the format of the JSON output.
5255

53-
By default, **null** values are not included in the output. You can use `INCLUDE_NULL_VALUES` to change this behavior.
56+
By default, **null** values aren't included in the output. You can use `INCLUDE_NULL_VALUES` to change this behavior.
5457

5558
Here's a sample query that uses **AUTO** mode with the `FOR JSON` clause.
5659

57-
```sql
58-
SELECT name, surname
59-
FROM emp
60+
```sql
61+
SELECT name, surname
62+
FROM emp
6063
FOR JSON AUTO;
61-
```
64+
```
6265

6366
And here is the returned JSON.
6467

65-
```json
68+
```json
6669
[{
6770
"name": "John"
6871
}, {
@@ -73,71 +76,56 @@ And here is the returned JSON.
7376

7477
### 2.b - Example with JOIN and NULL
7578

76-
The following example of `SELECT...FOR JSON AUTO` includes a display of what the JSON results look like when there is a 1:Many relationship between data from `JOIN`'ed tables.
79+
The following example of `SELECT...FOR JSON AUTO` includes a display of what the JSON results look like when there is a *1:many* relationship between data from joined tables.
7780

7881
The absence of the null value from the returned JSON is also illustrated. However, you can override this default behavior by use of the `INCLUDE_NULL_VALUES` keyword on the `FOR` clause.
7982

8083
```sql
81-
go
82-
8384
DROP TABLE IF EXISTS #tabStudent;
8485
DROP TABLE IF EXISTS #tabClass;
86+
GO
8587

86-
go
87-
88-
CREATE TABLE #tabClass
89-
(
90-
ClassGuid uniqueIdentifier not null default newid(),
91-
ClassName nvarchar(32) not null
88+
CREATE TABLE #tabClass (
89+
ClassGuid UNIQUEIDENTIFIER NOT NULL DEFAULT newid(),
90+
ClassName NVARCHAR(32) NOT NULL
9291
);
9392

94-
CREATE TABLE #tabStudent
95-
(
96-
StudentGuid uniqueIdentifier not null default newid(),
97-
StudentName nvarchar(32) not null,
98-
ClassGuid uniqueIdentifier null -- Foreign key.
93+
CREATE TABLE #tabStudent (
94+
StudentGuid UNIQUEIDENTIFIER NOT NULL DEFAULT newid(),
95+
StudentName NVARCHAR(32) NOT NULL,
96+
ClassGuid UNIQUEIDENTIFIER NULL -- Foreign key.
9997
);
98+
GO
10099

101-
go
102-
103-
INSERT INTO #tabClass
104-
(ClassGuid, ClassName)
105-
VALUES
106-
('DE807673-ECFC-4850-930D-A86F921DE438', 'Algebra Math'),
107-
('C55C6819-E744-4797-AC56-FF8A729A7F5C', 'Calculus Math'),
108-
('98509D36-A2C8-4A65-A310-E744F5621C83', 'Art Painting');
109-
110-
INSERT INTO #tabStudent
111-
(StudentName, ClassGuid)
112-
VALUES
113-
('Alice Apple', 'DE807673-ECFC-4850-930D-A86F921DE438'),
114-
('Alice Apple', 'C55C6819-E744-4797-AC56-FF8A729A7F5C'),
115-
('Betty Boot' , 'C55C6819-E744-4797-AC56-FF8A729A7F5C'),
116-
('Betty Boot' , '98509D36-A2C8-4A65-A310-E744F5621C83'),
117-
('Carla Cap' , null);
118-
119-
go
120-
121-
SELECT
122-
c.ClassName,
123-
s.StudentName
124-
FROM
125-
#tabClass as c
126-
RIGHT OUTER JOIN #tabStudent as s ON s.ClassGuid = c.ClassGuid
127-
ORDER BY
128-
c.ClassName,
129-
s.StudentName
130-
FOR
131-
JSON AUTO
132-
-- To include NULL values in the output, uncomment the following line:
133-
--, INCLUDE_NULL_VALUES
134-
;
100+
INSERT INTO #tabClass (ClassGuid, ClassName)
101+
VALUES
102+
('DE807673-ECFC-4850-930D-A86F921DE438', 'Algebra Math'),
103+
('C55C6819-E744-4797-AC56-FF8A729A7F5C', 'Calculus Math'),
104+
('98509D36-A2C8-4A65-A310-E744F5621C83', 'Art Painting');
105+
106+
INSERT INTO #tabStudent (StudentName, ClassGuid)
107+
VALUES
108+
('Alice Apple', 'DE807673-ECFC-4850-930D-A86F921DE438'),
109+
('Alice Apple', 'C55C6819-E744-4797-AC56-FF8A729A7F5C'),
110+
('Betty Boot', 'C55C6819-E744-4797-AC56-FF8A729A7F5C'),
111+
('Betty Boot', '98509D36-A2C8-4A65-A310-E744F5621C83'),
112+
('Carla Cap', null);
113+
GO
135114

115+
SELECT c.ClassName,
116+
s.StudentName
117+
FROM #tabClass AS c
118+
RIGHT JOIN #tabStudent AS s ON s.ClassGuid = c.ClassGuid
119+
ORDER BY c.ClassName,
120+
s.StudentName
121+
FOR JSON AUTO
122+
-- To include NULL values in the output, uncomment the following line:
123+
--, INCLUDE_NULL_VALUES
124+
;
136125
GO
137126

138127
DROP TABLE IF EXISTS #tabStudent;
139128
DROP TABLE IF EXISTS #tabClass;
140-
141129
GO
142130
```
143131

@@ -158,54 +146,55 @@ JSON_F52E2B61-18A1-11d1-B105-00805F49916B
158146

159147
For more detailed info and examples, see [Format JSON Output Automatically with AUTO Mode (SQL Server)](../../relational-databases/json/format-json-output-automatically-with-auto-mode-sql-server.md).
160148

161-
For syntax and usage, see [FOR Clause (Transact-SQL)](../../t-sql/queries/select-for-clause-transact-sql.md).
162-
163-
## Control other JSON output options
164-
Control the output of the `FOR JSON` clause by using the following additional options.
165-
166-
- **ROOT**. To add a single, top-level element to the JSON output, specify the **ROOT** option. If you don't specify this option, the JSON output doesn't have a root element. For more info, see [Add a Root Node to JSON Output with the ROOT Option (SQL Server)](../../relational-databases/json/add-a-root-node-to-json-output-with-the-root-option-sql-server.md).
167-
168-
- **INCLUDE_NULL_VALUES**. To include null values in the JSON output, specify the **INCLUDE_NULL_VALUES** option. If you don't specify this option, the output doesn't include JSON properties for NULL values in the query results. For more info, see [Include Null Values in JSON Output with the INCLUDE_NULL_VALUES Option (SQL Server)](../../relational-databases/json/include-null-values-in-json-include-null-values-option.md).
169-
170-
- **WITHOUT_ARRAY_WRAPPER**. To remove the square brackets that surround the JSON output of the `FOR JSON` clause by default, specify the **WITHOUT_ARRAY_WRAPPER** option. Use this option to generate a single JSON object as output from a single-row result. If you don't specify this option, the JSON output is formatted as an array - that is, it's enclosed within square brackets. For more info, see [Remove Square Brackets from JSON Output with the WITHOUT_ARRAY_WRAPPER Option (SQL Server)](../../relational-databases/json/remove-square-brackets-from-json-without-array-wrapper-option.md).
171-
172-
## Output of the FOR JSON clause
173-
The output of the `FOR JSON` clause has the following characteristics:
174-
175-
1. The result set contains a single column.
176-
- A small result set may contain a single row.
177-
- A large result set splits the long JSON string across multiple rows.
178-
- By default, SQL Server Management Studio (SSMS) concatenates the results into a single row when the output setting is **Results to Grid**. The SSMS status bar displays the actual row count.
179-
- Other client applications may require code to recombine lengthy results into a single, valid JSON string by concatenating the contents of multiple rows. For an example of this code in a C# application, see [Use FOR JSON output in a C# client app](../../relational-databases/json/use-for-json-output-in-sql-server-and-in-client-apps-sql-server.md#use-for-json-output-in-a-c-client-app).
180-
181-
:::image type="content" source="../../relational-databases/json/media/forjson-example2.png" alt-text="Example of FOR JSON output" lightbox="../../relational-databases/json/media/forjson-example2.png":::
182-
183-
184-
2. The results are formatted as an array of JSON objects.
185-
186-
- The number of elements in the JSON array is equal to the number of rows in the results of the SELECT statement (before the FOR JSON clause is applied).
187-
188-
- Each row in the results of the SELECT statement (before the FOR JSON clause is applied) becomes a separate JSON object in the array.
189-
190-
- Each column in the results of the SELECT statement (before the FOR JSON clause is applied) becomes a property of the JSON object.
191-
192-
3. Both the names of columns and their values are escaped according to JSON syntax. For more info, see [How FOR JSON escapes special characters and control characters (SQL Server)](../../relational-databases/json/how-for-json-escapes-special-characters-and-control-characters-sql-server.md).
149+
For syntax and usage, see [FOR Clause (Transact-SQL)](../../t-sql/queries/select-for-clause-transact-sql.md).
150+
151+
## Control other JSON output options
152+
153+
Control the output of the `FOR JSON` clause by using the following additional options.
154+
155+
- **ROOT**. To add a single, top-level element to the JSON output, specify the **ROOT** option. If you don't specify this option, the JSON output doesn't have a root element. For more info, see [Add a Root Node to JSON Output with the ROOT Option (SQL Server)](../../relational-databases/json/add-a-root-node-to-json-output-with-the-root-option-sql-server.md).
156+
157+
- **INCLUDE_NULL_VALUES**. To include null values in the JSON output, specify the **INCLUDE_NULL_VALUES** option. If you don't specify this option, the output doesn't include JSON properties for NULL values in the query results. For more info, see [Include Null Values in JSON Output with the INCLUDE_NULL_VALUES Option (SQL Server)](../../relational-databases/json/include-null-values-in-json-include-null-values-option.md).
158+
159+
- **WITHOUT_ARRAY_WRAPPER**. To remove the square brackets that surround the JSON output of the `FOR JSON` clause by default, specify the **WITHOUT_ARRAY_WRAPPER** option. Use this option to generate a single JSON object as output from a single-row result. If you don't specify this option, the JSON output is formatted as an array - that is, it's enclosed within square brackets. For more info, see [Remove Square Brackets from JSON Output with the WITHOUT_ARRAY_WRAPPER Option (SQL Server)](../../relational-databases/json/remove-square-brackets-from-json-without-array-wrapper-option.md).
160+
161+
## Output of the FOR JSON clause
162+
163+
The output of the `FOR JSON` clause has the following characteristics:
164+
165+
1. The result set contains a single column.
166+
- A small result set may contain a single row.
167+
- A large result set splits the long JSON string across multiple rows.
168+
- By default, SQL Server Management Studio (SSMS) concatenates the results into a single row when the output setting is **Results to Grid**. The SSMS status bar displays the actual row count.
169+
- Other client applications may require code to recombine lengthy results into a single, valid JSON string by concatenating the contents of multiple rows. For an example of this code in a C# application, see [Use FOR JSON output in a C# client app](../../relational-databases/json/use-for-json-output-in-sql-server-and-in-client-apps-sql-server.md#use-for-json-output-in-a-c-client-app).
170+
171+
:::image type="content" source="media/format-query-results-as-json-with-for-json-sql-server/for-json-output.png" alt-text="Screenshot of FOR JSON output in SQL Server Management Studio." lightbox="media/format-query-results-as-json-with-for-json-sql-server/for-json-output.png":::
172+
173+
1. The results are formatted as an array of JSON objects.
174+
175+
- The number of elements in the JSON array is equal to the number of rows in the results of the SELECT statement (before the FOR JSON clause is applied).
176+
177+
- Each row in the results of the SELECT statement (before the FOR JSON clause is applied) becomes a separate JSON object in the array.
178+
179+
- Each column in the results of the SELECT statement (before the FOR JSON clause is applied) becomes a property of the JSON object.
180+
181+
1. Both the names of columns and their values are escaped according to JSON syntax. For more info, see [How FOR JSON escapes special characters and control characters (SQL Server)](../../relational-databases/json/how-for-json-escapes-special-characters-and-control-characters-sql-server.md).
193182

194183
### Example
195-
Here's an example that demonstrates how the `FOR JSON` clause formats the JSON output.
196-
197-
**Query results**
184+
185+
Here's an example that demonstrates how the `FOR JSON` clause formats the JSON output.
186+
187+
#### Query results
198188

199189
|A|B|C|D|
200190
|-|-|-|-|
201191
|10|11|12|X|
202192
|20|21|22|Y|
203-
|30|31|32|Z|
204-
|   |   |   |   |
193+
|30|31|32|Z|
194+
195+
#### JSON output
205196

206-
**JSON output**
207-
208-
```json
197+
```json
209198
[{
210199
"A": 10,
211200
"B": 11,
@@ -221,28 +210,16 @@ Here's an example that demonstrates how the `FOR JSON` clause formats the JSON o
221210
"B": 31,
222211
"C": 32,
223212
"D": "Z"
224-
}]
225-
```
226-
227-
For more info about what you see in the output of the `FOR JSON` clause, see the following articles:
228-
229-
- [How FOR JSON converts SQL Server data types to JSON data types (SQL Server)](../../relational-databases/json/how-for-json-converts-sql-server-data-types-to-json-data-types-sql-server.md)
230-
The `FOR JSON` clause uses the rules described in this article to convert SQL data types to JSON types in the JSON output.
231-
232-
- [How FOR JSON escapes special characters and control characters (SQL Server)](../../relational-databases/json/how-for-json-escapes-special-characters-and-control-characters-sql-server.md)
233-
The `FOR JSON` clause escapes special characters and represents control characters in the JSON output as described in this article.
213+
}]
214+
```
234215

235-
## Learn more about JSON in SQL Server and Azure SQL Database
236-
237-
### Microsoft videos
216+
## See also
238217

239-
For a visual introduction to the built-in JSON support in SQL Server and Azure SQL Database, see the following videos:
218+
- [How FOR JSON converts SQL Server data types to JSON data types (SQL Server)](../../relational-databases/json/how-for-json-converts-sql-server-data-types-to-json-data-types-sql-server.md)
219+
- [How FOR JSON escapes special characters and control characters (SQL Server)](../../relational-databases/json/how-for-json-escapes-special-characters-and-control-characters-sql-server.md)
220+
- [JSON as a bridge between NoSQL and relational worlds](https://channel9.msdn.com/events/DataDriven-SQLServer2016/JSON-as-bridge-betwen-NoSQL-relational-worlds)
240221

241-
- [JSON as a bridge between NoSQL and relational worlds](https://channel9.msdn.com/events/DataDriven-SQLServer2016/JSON-as-bridge-betwen-NoSQL-relational-worlds)
242-
243222
## Next steps
244223

245-
- [FOR Clause (Transact-SQL)](../../t-sql/queries/select-for-clause-transact-sql.md)
246-
- [Use FOR JSON output in SQL Server and in client apps (SQL Server)](../../relational-databases/json/use-for-json-output-in-sql-server-and-in-client-apps-sql-server.md)
247-
248-
224+
- [FOR Clause (Transact-SQL)](../../t-sql/queries/select-for-clause-transact-sql.md)
225+
- [Use FOR JSON output in SQL Server and in client apps (SQL Server)](../../relational-databases/json/use-for-json-output-in-sql-server-and-in-client-apps-sql-server.md)
-55.8 KB
Binary file not shown.

docs/relational-databases/json/media/forjson-example2.png renamed to docs/relational-databases/json/media/format-query-results-as-json-with-for-json-sql-server/for-json-output.png

File renamed without changes.
56.6 KB
Loading
52.5 KB
Loading
-65.9 KB
Binary file not shown.

0 commit comments

Comments
 (0)