Search code examples
sql-server-2016

Select Json string with Select


I have following statement that I am trying to execute in Sql Server 2016 CTP 3:

DECLARE @json nvarchar(max)

set @json = '[ 
   { "name": "John" },
   { "name": "Jane", "surname": "Doe" }
]'

select
    'othervalue' as o,
    @json as j
for json path

The problem is when I execute these statements I get the following Json string (with escaped characters):

[{"o":"othervalue","j":"[ \r\n   { \"name\": \"John\" },\r\n   { \"name\": \"Jane\", \"surname\": \"Doe\" }\r\n]"}]

My question is how can select a Json string with a select statement correctly (without escaped characters).

Thanks


Solution

  • Wrap @json variable with JSON_QUERY:

    select
         'othervalue' as o,
          JSON_QUERY(@json) as j
    for json path
    

    See frequently asked questions on MSDN https://msdn.microsoft.com/en-us/library/mt631706.aspx