Escaping characters in T-SQL OPENJSON queries

牧云@^-^@ 提交于 2020-08-23 03:44:42

问题


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


回答1:


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'
    )


来源:https://stackoverflow.com/questions/45873125/escaping-characters-in-t-sql-openjson-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!