How to add new json field to existing json in groovy

My existing Json looks like this:

def json_req = "{\"date\":\"Tue, 06 Oct 2015 09:10:52 GMT\",\"nonce\":\"6cm7PmwDOKs\",\"devId\":\"<value>\",\"appId\":\"<value>\"}

Perform the operation, I can get the field sigwith the value. I need to add this extra field with a value as shown below:

"sig":"<value>"

So the new json looks like this:

def json_req = "{\"date\":\"Tue, 06 Oct 2015 09:10:52 GMT\",\"nonce\":\"6cm7PmwDOKs\",\"devId\":\"<value>\",\"appId\":\"<value>\",\"sig\":\"<value>\"}"

Inside the same script, can this new parameter be added with a value in json?

+4
source share
1 answer

You can parse json with JsonSlurper, and since the result of this is LazyMap, you can simply add a new entry to it (lines with printlnadded as hints):

import groovy.json.*

def json_req = '''{
"date":"Tue, 06 Oct 2015 09:10:52 GMT", 
"nonce":"6cm7PmwDOKs",
"devId":"<value>",
"appId": "<value>"
}'''

def json = new JsonSlurper().parseText(json_req)
println json.getClass().getName()
json << [sig: "<value>"] // json.put('sig', '<value>')
println JsonOutput.toJson(json)

Try it on the groovy web console

+7
source

Source: https://habr.com/ru/post/1610552/


All Articles