简体   繁体   English

如何使用Groovy将元素添加到JSON的嵌套元素中

[英]How to add an element to a nested element of json using groovy

I have some JSON data like the one below and want to add another county with a city name. 我有一些像下面这样的JSON数据,并且想要添加另一个具有城市名称的县。 How do I add it? 如何添加?

My current JSON data looks like the following: 我当前的JSON数据如下所示:

{
    "state" : "WA",
    "county" : {
        "king" : {
            "Seattle" : [ "r", "d", "n" ],
            "Kirkland" : [ "r", "d", "w" ]
        },
        "queen" : {
            "Edmonds" : [ "r" ]
        }
    }
}

Expected JSON data should look like the following: 预期的JSON数据应如下所示:

{
    "state" : "WA",
    "county" : {
        "king" : {
            "Seattle" : [ "r", "d", "n" ],
            "Kirkland" : [ "r", "d", "w" ]
        },
        "queen" : {
            "Edmonds" : [ "r" ]
        }
        "prince" : {
            "Lynnwood" : [ "r", "d", "w" ]
        }
    }
}

Using the "Append json into a json in groovy", I was able to get it to work. 使用“在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM