在SQL Server中检查唯一的JSON密钥

时间:2018-10-03 16:08:17

标签: json sql-server

在SQL Server中,如何检查字符串是否为有效的JSON并且密钥都是唯一的?

根据T-SQL documentation,常规的ISJSON方法不会检查同一级别上的键是否唯一。

1 个答案:

答案 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