Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Groovy JsonBuilder add array element in 'for' loop

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    "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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading