You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL中使用OPENJSON解析数字键名JSON时出现路径格式错误

问题:OPENJSON解析数字键名JSON时出现路径格式错误

编写的SQL代码如下:

Insert into dbo.Data (
    COL_0
)
select
        A_1
from OPENJSON (@jsonData)
    with (
        A_1 nvarchar(max)   '$.0'
)

执行时触发异常:

ex  {System.Data.SqlClient.SqlException (0x80131904): JSON path is not properly formatted. Unexpected character '0' is found at position 2.    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)    at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)    at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)    at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)    at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)    at System.Data.SqlClient.SqlCommand.CompleteAsyncExecuteReader()    at System.Data.SqlClient.SqlCommand.EndExecu…   

对应的JSON结构:

[{"0":"","1":"January 1, 2024"}]

猜测问题与数字字段名有关,请求解答。


解决方案

问题确实出在数字键名的JSON路径写法上。SQL Server的OPENJSON对纯数字的JSON属性名有特殊要求,不能直接使用$.0这种格式,必须将数字键名用引号包裹起来。

修正后的SQL代码有两种写法:

写法1:使用双引号包裹键名

Insert into dbo.Data (
    COL_0
)
select
        A_1
from OPENJSON (@jsonData)
    with (
        A_1 nvarchar(max)   '$."0"'
)

写法2:使用单引号包裹键名

Insert into dbo.Data (
    COL_0
)
select
        A_1
from OPENJSON (@jsonData)
    with (
        A_1 nvarchar(max)   '$[\'0\']'
)

修改后,OPENJSON就能正确识别数字类型的键名,正常解析JSON数据。

内容的提问来源于stack exchange,提问作者Qiuzman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 05:42:48