How FOR JSON escapes special characters and control characters (SQL Server)

THIS TOPIC APPLIES TO: yesSQL ServeryesAzure SQL DatabasenoAzure SQL Data Warehouse noParallel Data Warehouse

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 - http://www.ietf.org/rfc/rfc4627.txt.

Escaping of special characters

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

Control characters

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

Example

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"
}

Learn more about JSON in SQL Server and Azure SQL Database

Microsoft blog posts

For specific solutions, use cases, and recommendations, see these blog posts about the built-in JSON support in SQL Server and Azure SQL Database.

Microsoft videos

For a visual introduction to the built-in JSON support in SQL Server and Azure SQL Database, see the following videos:

See Also

Format Query Results as JSON with FOR JSON (SQL Server)
FOR Clause