在SQL Server中,如何检查字符串是否为有效的JSON并且密钥都是唯一的?
根据T-SQL documentation,常规的ISJSON方法不会检查同一级别上的键是否唯一。
答案 0 :(得分:0)
您可以使用Recursive Common Table Expression来执行此操作。像这样的东西:
DECLARE @json NVARCHAR(4000) = N'{
"StringValue":"John",
"IntValue":45,
"TrueValue":true,
"FalseValue":false,
"NullValue":null,
"ArrayValue":["a","r","r","a","y"],
"ObjectValue":{"obj":"ect"}
}';
with q as
(
select [key] path, [key], value, type, 0 level
from openjson(@json)
union all
select concat(q.path,'\',n.[key]), n.[key], n.value, n.type, q.level + 1
from q
cross apply openjson(q.value) n
where q.type in (4,5)
)
select *, count(*) over (partition by path) pathCount
from q