[英]How to add an element to a nested element of json using groovy
我有一些像下面这样的JSON数据,并且想要添加另一个具有城市名称的县。 如何添加?
我当前的JSON数据如下所示:
{
"state" : "WA",
"county" : {
"king" : {
"Seattle" : [ "r", "d", "n" ],
"Kirkland" : [ "r", "d", "w" ]
},
"queen" : {
"Edmonds" : [ "r" ]
}
}
}
预期的JSON数据应如下所示:
{
"state" : "WA",
"county" : {
"king" : {
"Seattle" : [ "r", "d", "n" ],
"Kirkland" : [ "r", "d", "w" ]
},
"queen" : {
"Edmonds" : [ "r" ]
}
"prince" : {
"Lynnwood" : [ "r", "d", "w" ]
}
}
}
使用“在groovy中将json附加到json中”,我能够使其工作。
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()
您可以从这里获得答案:- 将json附加到groovy中的json中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.