Forum Discussion

SK07's avatar
SK07
Contributor
7 years ago

Groovy- count all nulls in an array

I want to print  how many nulls, 1's and 2's seperately.

Json : {"prods": [{"Item":13,"rate":200, "Ids": []}, {"Item":13,"rate":200, "Ids": []}, 
{"Item":11,"rate": 100, "Ids": [ {"level": 1}]}, 
{"Item":13,"rate":200, "Ids": [ {"level": 1}]},
{"Item":12,"rate":200, "Ids": [ {"level": 2} ], [{"level": 2}, {"level": 2}]} ]}.

 

I tried and couldnt get the counts seperately.def jsonids = json.Ids
log.info jsonids
[[], [], [1], [1], [2, 2, 2]]

I want the results like below:

Level []: 2, Level 1: 2,  Level 2: 3

Any help is appreciated.

 

 

Nulls: 2

  • aaronpliu's avatar
    aaronpliu
    Frequent Contributor

    Hi SK07,

     

    I believe you should can get solution from scripts which I replied to you in your previous topic, right?

     

    firstly, you should parse json string as a json object, right? you should do this at first step.

    secondly, retrieve 'Ids' and get content. (if "Ids" 's value is always like []. if not, you can add a 'if' condition to determine, like: if(a instanceof ArrayList),    a means Ids' value)

    thirdly, you also get all values of Ids, so you can count the numer of them.

     

    If any enquires, please post your questions here

     

    Regards,

    /Aaron

    • SK07's avatar
      SK07
      Contributor

      Hi Aaron, This is something different from previous with inner loops.

      Json : {"prods": [{"Item":13,"rate":200, "Ids": []},
                                {"Item":14,"rate":300, "Ids": []},
                                {"Item":15,"rate":100, "Ids": [ {"level": 1}]},
                                {"Item":16,"rate":700, "Ids": [ {"level": 1}]},
                                {"Item":17,"rate":500, "Ids": [ {"level": 2} ], [{"level": 2}, {"level": 2}]} ]}.

      So, I retrieve the Ids as below:

      def jsonids = json.Ids
      log.info jsonids
      [[], [], [1], [1], [2, 2, 2]]

      But I dont how to read/count the above and get the results like below:

      Ids [] =: 2, Level 1 =  2, Level 2 = 3

      • aaronpliu's avatar
        aaronpliu
        Frequent Contributor

        Hi SK07,

         

        Dont think of it to be complex. If you only wanna count the number of "[]", try

        // your list aa=[[], [], [1,1],[2,2,2]]
        def num = 0
        for(item in aa){
            if(item.size() < 1) num++
        }
        log.info "[Ids []: $num]"

         

        Regards,

        /Aaron