Showing posts with label json. Show all posts
Showing posts with label json. Show all posts

Tuesday, March 18, 2008

Using JSON Builder with collections

I was having a particular time, doing what I thought would be an easy task. I wanted to use the JSON Builder that would create JSON syntax that I use with the Ext JS framework. I needed JSON to look like this:

{
success:true,
count:1,
data: [
{id:1,task:'Home Page is waiting to be promoted'}
]
}


However no matter what I tried I couldn't get the "data" array to be generated properly. The data elements within the array were being created outside the array. After enough persistence I was finally able to get it to work with this:

def tasks = .... // an array of tasks

render(builder:'json') {
success(true)
count(tasks.size())
data {
tasks.each {
data(
id: it.id,
task: it.task
)
}
}
}



Notice I had to duplicate "data" twice, once outside of the each loop and once inside. I really don't understand why, I'm just glad I figured it out and I can move on! Hopefully this will help if you are stuck with creating arrays with the JSON Builder.