如何使用groovy将元素添加到json的嵌套元素

时间:2017-08-08 20:38:11

标签: json

我有一些类似下面的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" ]
        }
    }
}

2 个答案:

答案 0 :(得分:1)

使用"将json添加到groovy"中的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()

答案 1 :(得分:0)

您可以从这里得到答案: - Append json into a json in groovy