| title | How FOR JSON escapes special characters and control characters | |
|---|---|---|
| ms.date | 03/16/2017 | |
| ms.prod | sql | |
| ms.reviewer | genemi | |
| ms.technology | ||
| ms.topic | conceptual | |
| helpviewer_keywords |
|
|
| ms.assetid | 4ba90025-5a09-4f0a-836a-54c886324530 | |
| author | jovanpop-msft | |
| ms.author | jovanpop | |
| ms.custom | seo-dt-2019 | |
| monikerRange | =azuresqldb-current||>=sql-server-2016||=sqlallproducts-allversions||>=sql-server-linux-2017||=azuresqldb-mi-current |
[!INCLUDEappliesto-ss-asdb-xxxx-xxx-md]
This topic describes how the FOR JSON clause of a SQL Server SELECT statement escapes special characters and represents control characters in the JSON output.
Important
This page describes the built-in support for JSON in Microsoft SQL Server. For general info about escaping and encoding in JSON, see Section 2.5 of the JSON RFC - https://www.ietf.org/rfc/rfc4627.txt.
If the source data contains special characters, the FOR JSON clause escapes them in the JSON output with \, as shown in the following table. This escaping occurs both in the names of properties and in their values.
| Special character | Escaped output |
|---|---|
| Quotation mark (") | \" |
| Backslash (\) | \| |
| Slash (/) | \/ |
| Backspace | \b |
| Form feed | \f |
| New line | \n |
| Carriage return | \r |
| Horizontal tab | \t |
If the source data contains control characters, the FOR JSON clause encodes them in the JSON output in \u<code> format, as shown in the following table.
| Control character | Encoded output |
|---|---|
| CHAR(0) | \u0000 |
| CHAR(1) | \u0001 |
| ... | ... |
| CHAR(31) | \u001f |
Here's an example of the FOR JSON output for source data that includes both special characters and control characters.
Query:
SELECT
'VALUE\ /
"' as [KEY\/"],
CHAR(0) as '0',
CHAR(1) as '1',
CHAR(31) as '31'
FOR JSON PATH Result:
{
"KEY\\\t\/\"": "VALUE\\\t\/\r\n\"",
"0": "\u0000",
"1": "\u0001",
"31": "\u001f"
}For a visual introduction to the built-in JSON support in SQL Server and Azure SQL Database, see the following videos:
Format Query Results as JSON with FOR JSON (SQL Server)
FOR Clause