Reputation: 21
I have some JSON data like the one below and want to add another county with a city name. How do I add it?
My current JSON data looks like the following:
{
"state" : "WA",
"county" : {
"king" : {
"Seattle" : [ "r", "d", "n" ],
"Kirkland" : [ "r", "d", "w" ]
},
"queen" : {
"Edmonds" : [ "r" ]
}
}
}
Expected JSON data should look like the following:
{
"state" : "WA",
"county" : {
"king" : {
"Seattle" : [ "r", "d", "n" ],
"Kirkland" : [ "r", "d", "w" ]
},
"queen" : {
"Edmonds" : [ "r" ]
}
"prince" : {
"Lynnwood" : [ "r", "d", "w" ]
}
}
}
Upvotes: 0
Views: 6103
Reputation: 21
Using the "Append json into a json in groovy", I was able to get it to work.
import groovy.json.*
String[] myArray = [ "r", "d", "w" ]
def builder = new JsonBuilder()
def root = builder.event{
"Lynnwood" myArray
}
def json = new JsonSlurper().parseText('''{ "state" : "WA", "county" : { "king" : { "Seattle" : [ "r", "d", "n" ], "Kirkland" : [ "r", "d", "w" ] }, "queen" : { "Edmonds" : [ "r" ] } } }''')
// Append the built JSON to the "slurped" JSON
json.county.prince = root.event
// Re-build the JSON so it can saved as a String
new JsonBuilder(json).toPrettyString()
Upvotes: 2
Reputation: 374
You can get your answer from here :- Append json into a json in groovy
Upvotes: 0