Skip to content
Advertisement

SQL Query to get the count of Json Array

I have the below Json object. How do I get the count of Object Array.

{
  "Model": [
    {
  "ModelName": "Test Model",    
  "Object": [
     {
       "ID": 1,
       "Name": "ABC"           

     },
     {
       "ID": 11,
       "Name": "ABCD"          
    },         
 ]  
 }]}

I tried the below query but seems JSON_Length was not available.

SELECT ModelName,
       JSON_LENGTH(JsonData, '$.Model[0].Object')
    FROM TabA

The expected output should be

 ModelName      COUNT
 Test Model      2

Advertisement

Answer

If you have valid JSON (at the moment you have a trailing comma (,_ after one of your closing braces (})), then you could use OPENJSON and COUNT:

DECLARE @JSON nvarchar(MAX) = N'{
  "Model": [
    {
  "ModelName": "Test Model",    
  "Object": [
     {
       "ID": 1,
       "Name": "ABC"           

     },
     {
       "ID": 11,
       "Name": "ABCD"          
    }         
 ]  
 }]}';

SELECT M.ModelName,
       COUNT(O.[key]) AS [Count]
FROM (VALUES(@JSON))V(J)
     CROSS APPLY OPENJSON(V.J)
                 WITH(ModelName varchar(20) '$.Model[0].ModelName',
                      [Object] nvarchar(MAX) '$.Model[0].Object' AS JSON) M
     CROSS APPLY OPENJSON(M.[Object]) O
GROUP BY M.ModelName;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement