Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new json field to existing json in groovy

Tags:

json

groovy

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?

like image 744
Hanumanth Avatar asked Oct 07 '15 09:10

Hanumanth


People also ask

How do I add a JSON string to an existing JSON file in Java?

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.

What is groovy JSON JsonSlurper?

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.


1 Answers

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

like image 103
jalopaba Avatar answered Sep 29 '22 07:09

jalopaba