简体   繁体   中英

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. 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" ]
        }
    }
}

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()

您可以从这里获得答案:- 将json附加到groovy中的json中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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