Iterate through JSONObject

2.2k views Asked by At

I am working on writing a groovy script now and I am absolute new in groovy lang.

I have Json Object, like that:

{
   "firstVar": {
       "active": "false",
       "title": "First Var"
   },
   "secondVar": {
       "active": "false",
       "title": "Second Var"
   }
}

I need to iterate over this Json object. Count of items in this object may be various, like "sixthVar". I know solution in Java, and need something similar in groovy:

JSONObject jsonObject = new JSONObject(contents.trim());
Iterator<String> keys = jsonObject.keys();

while(keys.hasNext()) {
    String key = keys.next();
    if (jsonObject.get(key) instanceof JSONObject) {
          // do something with jsonObject here      
    }
}

Or maybe there are some way to convert Json object to Json array?

1

There are 1 answers

1
kairatawer On BEST ANSWER

I found the solution by trial and error. There is way of iteration like in Json Array:

jsonObject.each {
    // do something with it.key and it.value pair
}