[英]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.