Forum Discussion

SK07's avatar
SK07
Contributor
7 years ago

Json response for inner loop

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


I'm trying to groupby an attribute LEVEL and get a sum of it....

I could get it  correctly only for which the level has  1.
But I couldnt get the result as expected for level 2 as its has an inner loop...
I'm looking for a result as: Level: 1, Count per level : [1: 50]
                                          Level: 2, Count per level : [2.25]

 

Appreciate your help!

  • Hi SK07,

     

    Getting your point and give u a solution below:

    //YourJsonData
    def data = new groovy.json.JsonSlurper().parseText(YourJsonData)
    def aa = []
    data.prods.each{id ->
        aa << id.ids.collect{le ->
            le.level
            }
    }
    
    def bb = aa.flatten()
    aa.flatten().unique().each{a ->
        def count = 0
        for(b in bb){
            if(b == a) count++
            }
        // save your value if need
        log.info "[$a:$count]"
    }

    Hopefully above example can resolve your requirement.

     

     

    Thanks,

    /Aaron

  • aaronpliu's avatar
    aaronpliu
    Frequent Contributor

    Hi SK07                              ,

     

    Not sure what your expected result is. But seems you provided a wrong Json data??

    if you'd like to parse json data and get a sum of certain value, you may try like this:

    // YourJsonData
    def slurper = new groovy.json.JsonSlurper().parseText(YourJsonData)
    slurper.prods.each{id ->
        id.ids.each{le ->
             log.info le.level
            // you can process as you required
            }
    }
    • SK07's avatar
      SK07
      Contributor

      Thank you aaronpliu. I get the result as 1,2,2,1.

      I wanted to groupBy this as Level [ 1: 2], Level [2:2] for this result.

      • aaronpliu's avatar
        aaronpliu
        Frequent Contributor

        Hi SK07,

         

        Getting your point and give u a solution below:

        //YourJsonData
        def data = new groovy.json.JsonSlurper().parseText(YourJsonData)
        def aa = []
        data.prods.each{id ->
            aa << id.ids.collect{le ->
                le.level
                }
        }
        
        def bb = aa.flatten()
        aa.flatten().unique().each{a ->
            def count = 0
            for(b in bb){
                if(b == a) count++
                }
            // save your value if need
            log.info "[$a:$count]"
        }

        Hopefully above example can resolve your requirement.

         

         

        Thanks,

        /Aaron