Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping characters in T-SQL OPENJSON queries

I have the following JSON Data

DECLARE @jsonData NVARCHAR(MAX)
SET @jsonData =
'{  
   "insertions":[  
      {  
         "id":"58735A79-DEA8-462B-B3EB-C2797CA9D44E",
         "last-modified":"2017-08-08 13:07:32",
         "label":"HelloWorld1"
      },
      {  
         "id":"00565BCD-4240-46CF-A48F-849CB5A8114F",
         "last-modified":"2017-08-08 13:11:38",
         "label":"HelloWorld12"
      }
   ]
}'

And trying to perform a select from it:

SELECT
    *
FROM
    OPENJSON(JSON_QUERY(@jsonData,'$.insertions'))
WITH
    (uuid UNIQUEIDENTIFIER '$.id',
    modified DATETIME '$.last-modified',
    Label NVARCHAR(128) '$.label'
    )

It doesn't like the dash in the last-modified field.

Msg 13607, Level 16, State 4, Line 18
JSON path is not properly formatted. Unexpected character '-' is found at position 6.

Is there a way to escape the dash in the query? Everything works fine if there is no dash.

As required to support JSON, I'm using SQL Server 2016 with compatibility level = 130

like image 534
John Avatar asked Aug 25 '17 01:08

John


1 Answers

Adding double quotes around the field name seems to work

SELECT
    *
FROM
    OPENJSON(JSON_QUERY(@jsonData,'$.insertions'))
WITH
    (uuid UNIQUEIDENTIFIER '$.id',
    modified DATETIME '$."last-modified"',
    Label NVARCHAR(128) '$.label'
    )
like image 123
John Avatar answered Sep 25 '22 13:09

John