My existing Json looks like:
def json_req = "{\"date\":\"Tue, 06 Oct 2015 09:10:52 GMT\",\"nonce\":\"6cm7PmwDOKs\",\"devId\":\"<value>\",\"appId\":\"<value>\"}
Perform the operation I can get sig
field with value. I need to append this additional field with value as below:
"sig":"<value>"
So that the new json looks like:
def json_req = "{\"date\":\"Tue, 06 Oct 2015 09:10:52 GMT\",\"nonce\":\"6cm7PmwDOKs\",\"devId\":\"<value>\",\"appId\":\"<value>\",\"sig\":\"<value>\"}"
Within the same script can I append this new parameter with the value in json?
In the initial step, we can read a JSON file and parsing to a Java object then need to typecast the Java object to a JSonObject and parsing to a JsonArray. Then iterating this JSON array to print the JsonElement. We can create a JsonWriter class to write a JSON encoded value to a stream, one token at a time.
JsonSlurper is a class that parses JSON text or reader content into Groovy data structures (objects) such as maps, lists and primitive types like Integer , Double , Boolean and String . The class comes with a bunch of overloaded parse methods plus some special methods such as parseText , parseFile and others.
You can parse the json with JsonSlurper
, and since the result of that is a LazyMap
, you can simply add the new entry to it (lines with println
added 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With