简体   繁体   中英

Groovy Jsonslurper edit value in array

i searched and tried out a lot of things to solve my problem. But it seems that nothing will work. Maybe I just understand it wrong. I have a test.json File looking like this.

{
    "TEST-A":             [{ "app_id":"aaa" }],
    "TEST-B":              [{ "app_id":"bbb" }],
    "TEST-C":          [{ "app_id":"ccc" }]
}

and now i want to edit TEST-B with "xxx". What am i trying for example ist:

import groovy.json.JsonSlurper

def slurper = new groovy.json.JsonSlurper()
def inputFile = new File("../config/test.json")
def inputJSON = new JsonSlurper().parseText(inputFile.text)
def builder = new JsonBuilder(inputJSON)

builder.content.TEST-B[0] = 'xxx'

I thought that i already have a map to edit or do i need to use "assert"?

Greetings Frost.

The following code:

import groovy.json.*

def data = '''\
{
    "TEST-A":   [{ "app_id":"aaa" }],
    "TEST-B":   [{ "app_id":"bbb" }],
    "TEST-C":   [{ "app_id":"ccc" }]
}'''

def parsed = new JsonSlurper().parseText(data)
println "parsed is a java.util.Map: ${parsed instanceof Map}"

parsed.'TEST-B'[0].app_id = 'xxx'

println "map after change: $parsed"

def result = JsonOutput.toJson(parsed)
println "result is a String: ${result instanceof String}"

println "result: $result"
println "pretty result:\n${JsonOutput.prettyPrint(result)}"

when run, prints out:

~> groovy test.groovy
parsed is a java.util.Map: true
map after change: [TEST-A:[[app_id:aaa]], TEST-B:[[app_id:xxx]], TEST-C:[[app_id:ccc]]]
result is a String: true
result: {"TEST-A":[{"app_id":"aaa"}],"TEST-B":[{"app_id":"xxx"}],"TEST-C":[{"app_id":"ccc"}]}
pretty result:
{
    "TEST-A": [
        {
            "app_id": "aaa"
        }
    ],
    "TEST-B": [
        {
            "app_id": "xxx"
        }
    ],
    "TEST-C": [
        {
            "app_id": "ccc"
        }
    ]
}

and I believe accomplishes the essence of what you are trying to do. The thing to understand about JsonSlurper is after parsing the in-data, what you get back is a normal java.util.Map (or possibly a java.util.List depending on the in-data json).

In other words, the parsed variable above is just a Map where the keys are strings and the values are Lists of Maps.

The second thing to keep in mind is that keys like TEST-B are not valid indentifiers in groovy so you can not just write parsed.TEST-B because that would be interpreted as parsed.TEST - B , so you have to quote keys with special characters like this.

After you change the map and assuming you want to get back to a json representation, you have to use something like JsonOutput as in the code above.

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