Groovy JsonBuilder add array element in 'for' loop

Advertisements

I want to add array elements to my JSON in a ‘for()’ loop

  def builder = new JsonBuilder()
  def json = builder.si {
    content 'test'
  }
  json.si.put('myList',[])
  for (t=0; t < 2; t++) {
    json.si.myList.add({
      sval t.asString()
      ival t
    })

  }

the expected result is

{
    "si": {
        "content": "test",
        "myList": [
            {
                "sval": "0",
                "ival": 0
            },
            {
                "sval": "1",
                "ival": 1
            }
        ]
    }
}

but the resulting JSON is

{
    "si": {
        "content": "test",
        "myList": [
            {
                "sval": "2",
                "ival": 2
            },
            {
                "sval": "2",
                "ival": 2
            }
        ]
    }
}

as you can see I’m not able to put the current value of the ‘for’-variabel ‘t’ into the JSON array-entry. It always uses the value of ‘t’ after leaving the for-loop

why?

>Solution :

You may do it like that:

import groovy.json.JsonBuilder

def builder = new JsonBuilder()
def json = builder.si {
    content 'test'
}
json.si.put('myList', [])
for (t = 0; t < 2; t++) {
    json.si.myList.add([sval: t.toString(), ival: t])
}

println "JSON: ${builder.toPrettyString()}"

The problem in your implementation is that you don’t assign value directly, but rather you declare the closure that is executed "on demand", when you already left the loop.

Leave a ReplyCancel reply