Append json into a json in groovy - json

I am newbie to groovy. My requirement is i have to append a json into a json.My code as follows:
JSON constructed by me:
def builder = new groovy.json.JsonBuilder()
def root=builder.event{
type "model_output_load_init"
time new Timestamp(date.getTime())
status "success"
}
JSON from DB:
def json = rs.getString("status");
Now i have to append constructed into the JSON From DB. PLease help me to solve this.Thanks in advance.
EDIT:
My Constructed JSON:
{
"event": {
"type": "model_output_load_init",
"time": "2015-10-01T14:08:17+0000",
"status": "success"
}
}
JSON FROM DB:
{
"model_build": {
"Initialized": {
"Timestamp": ""
}
},
"modelExec": {
"Initialized": {
"Timestamp": ""
}
}
}
OUTPUT NEEDED:
{
"model_build": {
"Initialized": {
"Timestamp": ""
}
},
"modelExec": {
"Initialized": {
"Timestamp": ""
}
},
"event": {
"type": "model_output_load_init",
"time": "2015-10-01T14:08:17+0000",
"status": "success"
}
}

You can append to the Map generated by JsonSlurper.
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
def builder = new JsonBuilder()
def root = builder.event{
type "model_output_load_init"
time new Timestamp(date.getTime())
status "success"
}
// Simulates the JSON from DB
def json = new JsonSlurper().parseText('''
{
"model_build": {
"Initialized": {
"Timestamp": ""
}
},
"modelExec": {
"Initialized": {
"Timestamp": ""
}
}
}''')
// Append the built JSON to the "slurped" JSON
json.event = root.event
// Re-build the JSON so it can saved as a String
new JsonBuilder(json).toPrettyString()
The output looks like this:
{
"event": {
"type": "model_output_load_init",
"time": "2015-10-01T14:39:11+0000",
"status": "success"
},
"modelExec": {
"Initialized": {
"Timestamp": ""
}
},
"model_build": {
"Initialized": {
"Timestamp": ""
}
}
}

Related

Groovy unable to generate json output as needed

I'm trying to generate the following JSON output in Groovy for one of my Jenkins Job.
Expected JSON
{
"svc-a": {
"type": "object",
"properties": {
"svcVersion": {
"type": "string",
"propertyOrder": 1,
"enum": ["No build", "1.0.0.59", "1.0.0.58"]
},
"skipConfigs": {
"type": "boolean",
"format": "checkbox"
}
}
},
"svc-b": {
"type": "object",
"properties": {
"svcVersion": {
"type": "string",
"propertyOrder": 1,
"enum": ["No build", "1.0.0.177", "1.0.0.176", "1.0.0.175"]
},
"skipConfigs": {
"type": "boolean",
"format": "checkbox"
}
}
}
}
I am looping through each service and getting the build number from Jenkins. For each service I am trying to generate the json along with the some additional header and appending it to map. Finally when build the json object from map exisiting json is treated as string.
MyCode.
#!/usr/bin/env groovy
import org.boon.Boon;
import groovy.json.JsonSlurper;
import groovy.transform.Field;
import groovy.json.JsonBuilder;
import groovy.json.*
def serviceList = [
"svc-a",
"svc-b"
]
def getBuildVersions(serviceName) {
def resultList = []
resultList.add(0,"No build")
def job = jenkins.model.Jenkins.instance.getAllItems().findAll { it.name.contains(serviceName) }
job.each { s ->
if (s.toString().contains("")) {
print s
def builds = s.getBuilds()
builds.each { t->
if((t.result).toString() == "SUCCESS" && !t.displayName.contains("SNAPSHOT") && !t.displayName.contains("config")){
resultList.add(t.displayName)
}
}
}
}
return resultList
}
def retVal = new HashMap<String, Map>()
for (svc in serviceList) {
def myBuilds = getBuildVersions(svc)
List ver = myBuilds.collect{ "'" + it + "'"}
def header = """
{"type": "object", "properties": { "svcVersion": { "type": "string", "propertyOrder": 1, "enum": $ver }, "skipConfigs": { "type": "boolean", "format": "checkbox" } } }
"""
def json = JsonOutput.toJson(header)
def result = new JsonSlurper().parseText(json)
// s = "'" + svc + "'"
retVal.put(svc, result)
}
def builder = new JsonBuilder()
sjson = JsonOutput.toJson(retVal)
return sjson
Received Output
{"svc-a":"\n{\"type\": \"object\", \"properties\": { \"svcVersion\": { \"type\": \"string\", \"propertyOrder\": 1, \"enum\": ['No build', '1.0.0.59', '1.0.0.58', '1.0.0.57', '1.0.0.56', '1.0.0.55', '1.0.0.54', '1.0.0.53', '1.0.0.52', '1.0.0.51', '1.0.0.49', '1.0.0.48', '1.0.0.47', '1.0.0.46', '1.0.0.45', '1.0.0.38', '1.0.0.37', '1.0.0.36', '1.0.0.35', '1.0.0.33', '1.0.0.31', '1.0.0.30', '1.0.0.29', '1.0.0.28', '1.0.0.27', '1.0.0.26', '1.0.0.25', '1.0.0.24', '1.0.0.22', '1.0.0.20', '1.0.0.19', '1.0.0.18', '1.0.0.17', '1.0.0.16', '1.0.0.13', '1.0.0.11', '1.0.0.8', '1.0.0.6', '1.0.0.5'] }, \"skipConfigs\": { \"type\": \"boolean\", \"format\": \"checkbox\" } } }\n","svc-b":"\n{\"type\": \"object\", \"properties\": { \"svcVersion\": { \"type\": \"string\", \"propertyOrder\": 1, \"enum\": ['No build', '1.0.0.177', '1.0.0.176', '1.0.0.175', '1.0.0.173', '1.0.0.172', '1.0.0.171', '1.0.0.170', '1.0.0.169', '1.0.0.167', '1.0.0.166', '1.0.0.165', '1.0.0.164', '1.0.0.163', '1.0.0.162', '1.0.0.158', '1.0.0.156', '1.0.0.38', '1.0.0.37', '1.0.0.36', '1.0.0.35', '1.0.0.33', '1.0.0.31', '1.0.0.29', '1.0.0.27'] }, \"skipConfigs\": { \"type\": \"boolean\", \"format\": \"checkbox\" } } }\n"}
When the Groovy Map is converted to JSON, json object in the values treated as one string.
How can get the properly formatted json output. I come from python background dont have mcuh idea on Groovy.
Found the solution by just using string manipulation
for (svc in serviceList) {
def myBuilds = getBuildVersions(svc)
List ver = myBuilds.collect{ '"' + it + '"'}
def header = """
"$svc": {"type": "object", "properties": { "svcVersion": { "type": "string", "propertyOrder": 1, "enum": $ver }, "skipConfigs": { "type": "boolean", "format": "checkbox" } } }
"""
if (firstRun == "true"){
retVal = header
} else {
retVal = retVal + "," + header
}
firstRun = "false"
}

how to parse the json file and read the json elements in groovy

Hi i am trying to parse the below json file. I tried using jsonsluper and parsed the file. I executed below command. Nothing works.
def test =newjsonslurper().parsetext(organist)
test.resources.each{
println it.resources.metadata. "guid"
println it.resources.entity. "name"
}
This is the json file format
resources: [
{
"metadata" :{
"guid":"cya"
"url": "dummy.test"
},
"entity" :
{
"name": "system"
"status": "active"
}
}
{
"metadata" :
{
"guid":"cya"
"url": "dummy.test"
},
"entity" :
{
"name": "system"
"status": "active"
}
}
]
There were a couple of problems:
JsonSlurper().parseText() expects a String. If you're wanting to parse a file, use something like def response = new JsonSlurper().parse(new File('JsonFile.json'))
The JSON payload is not valid: it's missing a few brackets and commas.
The following code should work:
import groovy.json.JsonSlurper
def test = new JsonSlurper().parseText '''
{"resources": [
{
"metadata": {
"guid": "cya",
"url": "dummy.test"
},
"entity": {
"name": "system",
"status": "active"
}
},
{
"metadata": {
"guid": "cya",
"url": "dummy.test"
},
"entity": {
"name": "system",
"status": "active"
}
}
]}
'''
test.resources.each {
println it.metadata.guid
println it.entity.name
}

How to update a key value in JSON dynamically?

I have a JSON like below
{
"context":{
"parameters":[
{
"name":"stub",``
"value": {"item value":"abcdefg"}
},
{
"name":"category",
"value":{"item value":"cars"}
},
{
"name":"year",
"value":{"item value":"2012"}
},
{
"name":"make",
"value":{"item value":"toyota"}
},
{
"name":"cars",
"value":{"item value":"corolla"}
}
]
}
I am supplied with a two strings dynamically like "cars" and "accord". I need to search for "cars" and then replace the "item value" under it to "accord". I have tried to convert it to map but have no success.
Any suggestions about how I can achieve this?
Here's one way to do it in Groovy.
Assuming that the JSON is like so (I have corrected it; there are illegal chars in the original question):
def s = '''
{
"context":{
"parameters":[
{
"name":"stub",
"value": {"item value":"abcdefg"}
},
{
"name":"category",
"value":{"item value":"cars"}
},
{
"name":"year",
"value":{"item value":"2012"}
},
{
"name":"make",
"value":{"item value":"toyota"}
},
{
"name":"cars",
"value":{"item value":"corolla"}
}
]
}
}
'''
then consider:
import groovy.json.*
def jsonSlurper = new JsonSlurper().parseText(s)
def category = jsonSlurper.context.parameters.find { it.name == "cars" }
category.value."item value" = "accord"
println new JsonBuilder(jsonSlurper).toPrettyString()
you can do that with javascript. If you are working with JSON format you can parse that data to an object.
const data = JSON.parse("your json data")
data.context.parameters.map(param => {
if ( param.name !== "cars") {
return param
}
return {
"name": "cars",
value: {"accord": "corolla"}
}
})

How to create new JSON from JSON?

I have a JSON consisting of the following data:
{
"comment": {
"S": "Nice"
},
"id": {
"S": "1ca38300-8938-11e5-8656-9bf2d3249757"
},
"postId": {
"S": "083c1f50-8b84-11e5-9021-7da869825160"
},
"spam": {
"N": "0"
},
"tags": {
"L": [
{
"S": "test1"
},
{
"S": "test2"
}
]
}
}
And now, I want to format the above JSON to the following format, like:
{
"comment":"Nice",
"id":"1ca38300-8938-11e5-8656-9bf2d3249757",
"postId":"083c1f50-8b84-11e5-9021-7da869825160",
"tags":["test1","test2"]
}
Load your json and manipulate like a plain object and then save it.
Here is how to transform your object:
var newObj = {
comment: oldObj.comment.S,
id: oldObj.id.S,
postId: oldObj.postId.S,
tags: oldObj.tags.L.map(function (entry) {
return entry.S;
})
}
Hey find the below code
suppose ur above jsonObject is completely names are and placed under result Object.
JSONObject obj = new JSONObject();
obj.put("comment",result.getJSONObject("comment").getString("s"));
obj.put("id",result.getJSONObject("id").getString("s"));
obj.put("postId",result.getJSONObject("postId").getString("s"));
List<String> test = new ArrayList<String>;
JSONArray js = result.getJSONObject("tags").getJSONArray("L");
for(I=o;i<js.length();I++){
test.add(js.get(i).getString("s"));
}
obj.put("tags",test);

Groovy JsonBuilder array of objects

I have a JsonBuilder that I'm having some trouble with. I'd like the output to look like the following:
"unitTests": {
"testType": "TestNG",
"totalTests": 20,
"failedTests": 2,
"skippedTests": 0,
"failedTestList": [
{
"class": "SomeTestClass"
"method": "someTestMethod"
},
{
"class": "AnotherTestClass"
"method": "anotherTestMethod"
}
]
}
Instead what I am seeing is:
"unitTests": {
"testType": "TestNG",
"totalTests": 20,
"failedTests": 2,
"skippedTests": 0,
"failedTestList": [
[
{
"class": "SomeTestClass"
}
],
[
{
"method": "someTestMethod"
}
],
[
{
"class": "AnotherTestClass"
}
],
[
{
"method": "anotherTestMethod"
}
]
]
}
The code to generate the JSON document is below:
def json = new JsonBuilder()
def root = json {
time { $date timestamp }
data {
unitTests {
testType unitType
totalTests totalUnitTests
failedTests failedUnitTests
skippedTests skippedUnitTests
failedTestList(failedUnitTestClass.collect {[class: it]}, failedUnitTestMethod.collect {[method: it]})
}
}
}
There's a need to iterate both lists at the same time. Try:
[failedUnitTestClass, failedUnitTestMethod].transpose().collect { [class:it[0], method:it[1]] }
Full example:
import groovy.json.*
def json = new JsonBuilder()
def failedUnitTestClass = ['cls1', 'cls2', ]
def failedUnitTestMethod = ['m1', 'm2', ]
json.unitTests {
failedTestList([failedUnitTestClass, failedUnitTestMethod].transpose().collect {[class:it[0], method:it[1]]})
}
println JsonOutput.prettyPrint(json.toString())