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())
Related
I am trying to find the best way to compare 2 JSON Array objects using Groovy script.
JSON Obj1 =
{
"PO":
[
{
"OrderNumber": "12345",
"Location": "US",
}
{
"OrderNumber": "11223",
"Location": "US",
}
]
}
JSON Obj2 = {
"ResultPO":
[
{
"OrderNumber": "12345_00001",
"Location": "US",
"Customer": "ABC"
}
{
"OrderNumber": "98765_00002",
"Location": "US",
"Customer": "XYZ"
}
]
}
I need to return the JSON Output as below after finding the obj1 value in obj2 where OrderNumber is key identifier.
{
"ResultPO":
[
{
"OrderNumber": "12345_00001",
"Location": "US",
"Customer": "ABC"
}
]
}
Below is the sample code I have tried using JsonSlurper and findall but not able to get desired outcome.
def builder
def filterJson
filterJson = Obj2.findAll(){ it.OrderNumber.substring(0,4) == Obj1.OrderNumber.text()}
builder = new JsonBuilder(filterJson)
Try this one:
class OrderFilterSpec extends Specification {
def str1 = """{"PO":[
{"OrderNumber": "12345","Location": "US"},
{"OrderNumber": "11223","Location": "US"}
]}"""
def str2 = """{"ResultPO":[
{"OrderNumber": "12345_00001","Location": "US","Customer": "ABC"},
{"OrderNumber": "98765_00002","Location": "US","Customer": "XYZ"}
]}"""
def slurper = new JsonSlurper()
def buildResult(String first, String second) {
def (parsed1, parsed2) = [slurper.parseText(first), slurper.parseText(second)]
def filteredOrders = parsed2.ResultPO.findAll {
it.OrderNumber[0..4] in parsed1.PO.collect { it.OrderNumber }
}
return [ResultPO: filteredOrders]
}
def 'test order filtering'() {
expect:
buildResult(str1, str2) == [ResultPO: [[OrderNumber: '12345_00001', Location: 'US', Customer: 'ABC']]]
}
}
I have this json and I want to remove the field item.
{ "field": "AAA", "list": { "item": [ { "field01": "111", "field02": "222" }, { "field01": "333", "field02": "444" } ] }}
I'm using this json slurper groovy but it's returnung null.
def myJson = '..' //above json; def jsonParser = new JsonSlurper(); def jsonObject=jsonParser.parseText(myJson); return JsonOutput.toJson(jsonObject["item"])
The expected output is:
{ "field": "AAA", "list": [ { "field01": "111", "field02": "222" }, { "field01": "333", "field02": "444" } ]}
How can I do to remove the field "item"?
def myJson = '..' //above json;
def jsonParser = new JsonSlurper();
def jsonObject=jsonParser.parseText(myJson);
jsonObject.list=jsonObject.list.item
return JsonOutput.toJson(jsonObject)
How can I access "itemnumber" from this serializer?
Or how can I have a better serializer to access data in order_data[id][lot]['Qty'] format
{
"order_data": {
"id": [
{
"lot": {
"itemnumber": "sint ",
"Qty": 4
}
},
{
"lot": {
"itemnumber": "occa",
"Qty": 2
}
}
],
}
}
dt= AddItemsSerializer(data=request.data)
dt.is_valid(raise_exception=True)
order_data = dt.data.get('order_data')
Try this:
for id_dict in dt.data.get('order_data', {}).get('id', []):
print(id_dict.get('lot', {}).get('itemnumber'))
It will print out all values of itemnumber.
I'm attempting to parse Json using Groovy's jsonslurper. I'd like to drill down into the "id" and "label" elements and create a key:value pair from them. This is my attempt:
def slurper = new groovy.json.JsonSlurper()
def json = slurper.parseText(myjson)
result = [:]
json.each {
result.put(json.menu.items.id,json.menu.items.label)
}
println result
What I expect is a result of:
[ [Open, null], [OpenNew, Open New], [Zoomin, Zoom In], etc....]
What I get is one list of the id's and one list of the labels. Any suggestion on how to get the desired result? Here is the Json I'm feeding...
{
"menu":{
"header":"SVG Viewer",
"items":[
{
"id":"Open"
},
{
"id":"OpenNew",
"label":"Open New"
},
null,
{
"id":"ZoomIn",
"label":"Zoom In"
},
{
"id":"ZoomOut",
"label":"Zoom Out"
},
{
"id":"OriginalView",
"label":"Original View"
},
null,
{
"id":"Quality"
},
{
"id":"Pause"
},
{
"id":"Mute"
},
null,
{
"id":"Find",
"label":"Find..."
},
{
"id":"FindAgain",
"label":"Find Again"
},
{
"id":"Copy"
},
{
"id":"CopyAgain",
"label":"Copy Again"
},
{
"id":"CopySVG",
"label":"Copy SVG"
},
{
"id":"ViewSVG",
"label":"View SVG"
},
{
"id":"ViewSource",
"label":"View Source"
},
{
"id":"SaveAs",
"label":"Save As"
},
null,
{
"id":"Help"
},
{
"id":"About",
"label":"About Adobe CVG Viewer..."
}
]
}
}
You can do this
def result = new JsonSlurper()
.parseText(json)
.menu
.items
.findAll() // Throw away the 4 `null` ones
.collect { [ it.id, it.label ] }
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": ""
}
}
}