2

My JSON file

{
    "General": [
        {
            "AppUrl": "abc.com/",
            "HTTPResponseCode": "200",
            "QA Build Version#": "4.3.44"
        }
    ]
}

I want to get the count elements(key-value pairs) of the above JSON object.

I tried with the below code but it returns a count as 1.

My code

def InputJSON = new JsonSlurper().parse(new File(fileName))
def count = InputJSON.General.size()
Sathiamoorthy
  • 8,831
  • 9
  • 65
  • 77
Prabu
  • 3,550
  • 9
  • 44
  • 85
  • 2
    But there _is_ only one item in your `General` array. The array contains a single object with properties `AppUrl`, `HTTPResponseCode` and `QA Build Version#`. – Ivar Apr 06 '21 at 11:19
  • @Ivar Yes, you are correct, but I want to get the properties count inside the General Object. – Prabu Apr 06 '21 at 11:35
  • 1
    Okay, but what if there is a second item in the array? Do you want to count just those of the first item? Also what do you attempt to do with this count? (Maybe we can provide a better solution altogether if we know the context.) – Ivar Apr 06 '21 at 11:37
  • @Ivar i want to parse all the properties inside the General object and based on the count creating a loop get the key-value pair.instead of getting one by one. in feature it may increase the properties so that i reterive the count and looping with the size. – Prabu Apr 06 '21 at 11:44
  • @Ivar i want to parse all the properties inside the General object and based on the count creating a loop get the key-value pair.instead of getting one by one. in feature it may increase the properties so that i reterive the count and looping with the size. – Prabu Apr 06 '21 at 11:44
  • 2
    Could [this](https://stackoverflow.com/a/43824582) be a solution for you? Iterate over the items in `InputJSON.General` and then iterate over all the properties. So `InputJSON.General.each { row -> row.each { key, value -> println "$key : $value" } }` – Ivar Apr 06 '21 at 12:01
  • @Ivar Thanks it's helpful. – Prabu Apr 06 '21 at 12:22
  • 3
    Maybe you should rewrite this question to your actual problem. Getting the count was for a `for` limit? Or rather what relevance does it have for the later iterating? Otherwise it's `data.General*.size().sum()` for the total of all top level properties or `data.General*.size()` for a list. – cfrick Apr 06 '21 at 12:42
  • you want min, max or average count of items in each element? – injecteer Feb 17 '22 at 20:59

1 Answers1

1

Instead of:

def InputJSON = new JsonSlurper().parse(new File(fileName))
def count = InputJSON.General.size()

Should be:

def InputJSON = new JsonSlurper().parse(new File(fileName))
def count = InputJSON.General.keySet().size()
Kyle Devoe
  • 11
  • 1