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

7jmck4yq  于 2022-11-19  发布在  其他
关注(0)|答案(2)|浏览(148)

假设有一个表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;

是否有语法可以忽略大小写,同时返回Commentcomment属性。

4ngedf3f

4ngedf3f1#

如文档中所述,通过显式架构(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
fkaflof6

fkaflof62#

我知道现在给予答案已经太晚了,但对于社区来说,最简单的解决方法是对json字符串应用LOWER或UPPER函数。

SET @Information = LOWER(@Information)

SELECT jsonInfo.*
FROM OPENJSON(@Information, N'$')
WITH(
    Comment NVARCHAR(MAX) N'$.comment',
    TimeStamp DATETIME'$.timestamp'
) AS jsonInfo;

相关问题