Reputation: 35928
I have JSON that looks similar to this:
{"test":{"red":"on","green":"off","yellow":"on"},"test1":{"red":"off","green":"on","yellow":"off"},"test2":{"red":"on","green":"off","yellow":"off"}}
I've iterating over this with the code below:
JSONObject t = JSON.parse(params.myObject)
t.each { id, data ->
println id
println data.red
println data.green
println data.yellow
}
However, at times I can have dynamically different values in the JSON Object. For example (new color added):
{"test":{"red":"on","green":"off","yellow":"on","pink":"on"},"test1":{"red":"off","green":"on","yellow":"off","pink":"on"},"test2":{"red":"on","green":"off","yellow":"off","pink":"on"}}
Question
Is there a way to iterate over all the json without hardcoding the colors in my code?
Upvotes: 2
Views: 701
Reputation: 14853
JSONObject t = JSON.parse(params.myObject)
t.each { id, data ->
println id
data.each { prop, value ->
println prop + " = " + value
}
}
Upvotes: 3
Reputation: 35928
I figured it out.
I can simply just iterate over the values in similar fashion:
t.each { id, data ->
println id
data.each {id1, d ->
println id1
println d
}
}
Upvotes: 0