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
1
  • 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. Commented May 14, 2020 at 9:48

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

0

A simplified version of @Thom A's answer use OPENJSON and COUNT:, by eliminating the CROSS APPLYs:

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

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

select [ModelName] = JSON_value(@JSON, N'$.Model[0].ModelName')
     , [COUNT]     = count(*) 
  from openJSON(@JSON, N'$.Model[0].Object');

result:

ModelName COUNT
Test Model 2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.