5

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
Ashok Yaganti
  • 173
  • 5
  • 14
  • The JSON you've provided isn't valid; unless you have valid JSON, you won't be able to use any of the JSON functions. – Thom A May 14 '20 at 09:48

1 Answers1

3

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;
Thom A
  • 88,727
  • 11
  • 45
  • 75