OPENJSON 在解析 JSON 属性时忽略大小写

OPENJSON to ignore case when parsing JSON properties

假设有一个 table A 具有列 Information,并且数据以 JSON 格式存储在那里。 JSON 字符串,存储在那里,可能具有属性 CommentTimestamp 或属性 commenttimestamp。像这样:

[{"Timestamp":"2018-04-11 18:14:59.9708","Comment":"first comment"}]
[{"timestamp":"2017-04-11 18:14:59.9708","comment":"second comment"}]
[{"Timestamp":"2019-04-11 18:14:59.9708","Comment":"third comment"}, {"timestamp":"2017-04-11 18:14:59.9708","comment":"last comment"}]

下面的脚本只为大写属性解析 JSON 字符串,并为小写的 JSON 字符串抛出错误。

Select jsonInfo.*
From OPENJSON(@Information, N'$')
    with(
        Comment nvarchar(max) N'$.Comment',
        TimeStamp datetime '$.Timestamp'
    ) as jsonInfo;

是否有任何语法 return 同时具有 Commentcomment 属性,忽略大小写。

documentation 中所述,使用显式模式(WITH 子句),OPENJSON() 将输入 JSON 表达式中的键与WITH 子句和匹配区分大小写。但是,作为一种可能的解决方法,您可以尝试将 OPENJSON() 与默认架构和条件聚合一起使用:

声明:

DECLARE @information nvarchar(max) = N'[
   {"Timestamp":"2019-04-11 18:14:59.9708","Comment":"third comment"}, 
   {"timestamp":"2017-04-11 18:14:59.9708","comment":"last comment"}
]'

SELECT 
   MAX(CASE WHEN LOWER(j2.[key]) = N'timestamp' THEN j2.[value] END) AS [TimeStamp],
   MAX(CASE WHEN LOWER(j2.[key]) = N'comment' THEN j2.[value] END) AS [Comment]
FROM OPENJSON(@information, '$') j1
CROSS APPLY OPENJSON(j1.[value]) j2
GROUP BY j1.[key]

结果:

TimeStamp                   Comment
-----------------------------------------
2019-04-11 18:14:59.9708    third comment
2017-04-11 18:14:59.9708    last comment