Groovy script to compare 2 JSON array objects - json

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']]]
}
}

Related

Preparing JSON array of Objects from multiple array list

I am very new to the Groovy scripts and would like to build a JSON output from the below JSON input. Kindly help!
My JSON input looks like this:
{
"id":"1222",
"storageNode": {
"uuid": "22255566336",
"properties": {
"BuinessUnit": [
"Light",
"Fan",
"Watch"
],
"Contact": [
"abc#gmail.com",
"fhh#gmail.com"
],
"Location": [
"Banglore",
"Surat",
"Pune"
]
}
}
}
Expected Output:
[
{
"BuinessUnit": "Light",
"Contact": "abc#gmail.com",
"Location": "Banglore"
},
{
"BuinessUnit": "Fan",
"Contact": "fhh#gmail.com",
"Location": "Surat"
},
{
"BuinessUnit": "Watch",
"Contact": "",
"Location": "Pune"
}
]
Please note that in case any array is not matching the value count that will always be the last one and in that case, a blank value ("") has to be populated. The "BusinessUnit" object can be referred for array size validation.
My code looks like this:
import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import groovy.json.*;
def Message processData(Message message) {
//Body
def body = message.getBody(String.class);
def jsonSlurper = new JsonSlurper()
def list = jsonSlurper.parseText(body)
String temp
def BU = list.storageNode.properties.get("BusinessUnit")
def builder = new JsonBuilder(
BU.collect {
[
BusinessUnit: it
]
}
)
message.setBody(builder.toPrettyString())
return message
}
It is only returning this:
[
{
"BusinessUnit": "Light"
},
{
"BusinessUnit": "Fan"
},
{
"BusinessUnit": "Watch"
}
]
Now how will I add other parts to it? Please help!
I have come up with the following solution that converts source JSON string to the target JSON string:
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
def json = '''
{
"id":"1222",
"storageNode": {
"uuid": "22255566336",
"properties": {
"BusinessUnit": [
"Light",
"Fan",
"Watch"
],
"Contact": [
"abc#gmail.com",
"fhh#gmail.com"
],
"Location": [
"Banglore",
"Surat",
"Pune"
]
}
}
}
'''
println convert(json)
String convert(String json) {
def list = new JsonSlurper().parseText(json)
List<String> units = list.storageNode.properties.BusinessUnit
List<String> contacts = list.storageNode.properties.Contact
List<String> locations = list.storageNode.properties.Location
def result = []
units.eachWithIndex { unit, int index ->
result << [
BusinessUnit: unit,
Contact : contacts.size() > index ? contacts[index] : '',
Location : locations.size() > index ? locations[index] : '',
]
}
return new JsonBuilder(result).toPrettyString()
}
I've omitted the logic of getting string from the message and packaging transformed JSON into message.
I hope it will help you to move forward. Please let me know if you need further assistance here.
You can use the built-in Groovy facilities, like transpose():
import groovy.json.*
def json = new JsonSlurper().parseText '''{ "id":"1222", "storageNode": { "uuid": "22255566336", "properties": {
"BuinessUnit": [ "Light", "Fan", "Watch" ],
"Contact": [ "abc#gmail.com", "fhh#gmail.com" ],
"Location": [ "Banglore", "Surat", "Pune" ] } } }'''
def names = json.storageNode.properties*.key
def values = json.storageNode.properties*.value
int maxSize = values*.size().max()
// pad lists with trainiling spaces
values.each{ v -> ( maxSize - v.size() ).times{ v << '' } }
def result = values.transpose().collect{ tuple -> [ names, tuple ].transpose().collectEntries{ it } }
assert result.toString() == '[[BuinessUnit:Light, Contact:abc#gmail.com, Location:Banglore], [BuinessUnit:Fan, Contact:fhh#gmail.com, Location:Surat], [BuinessUnit:Watch, Contact:, Location:Pune]]'
This piece of code can process everything under storageNode.properties.

groovy to remove json unwated array label

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)

Terraform: JSON Path Query doesn't work in terraform

I have data like below in json file site24x7IPs.json, and new filter it in terraform:
{
"LocationDetails": [
{
"IPv6_Address_External": "2803:eb80:4000:d::0/64",
"City": "Buenos Aires",
"Place": "Argentina",
"external_ip": "170.78.75.88"
},
{
"IPv6_Address_External": "",
"City": "Buenos Aires",
"Place": "Argentina",
"external_ip": "170.78.75.87"
},
{
"IPv6_Address_External": "",
"City": "Melbourne",
"Place": "Australia",
"external_ip": "103.91.166.0/24"
}
]
}
And terraform code:
locals {
site24x7IPs = jsondecode(file("${path.module}/site24x7IPs.json"))
}
output "site24x7IPs" {
#value = local.site24x7IPs.LocationDetails[*].external_ip # This works
# I'd like to filter the IP from Australia,
value = local.site24x7IPs.LocationDetails[?(#.Place == "Australia")].external_ip
}
Expecting Result:
"103.91.166.0/24"
Output:
value = local.site24x7IPs.LocationDetails[?(#.Place == "Australia")].external_ip
This character is not used within the language.
.LocationDetails[?(#.Place == "Australia")].external_ip is the JSON query syntax, but it doesn't work in Terraform.
Is there a similar way to achieve the filtering goal in Terraform?
Thanks,
This should give you the result:
output "australia_ip_with_quotes" {
value = format("%q",element([for i in local.site24x7IPs.LocationDetails: i.external_ip if i.Place == "Australia"],0))
}
output "australia_ip_without_quotes" {
value = element([for i in local.site24x7IPs.LocationDetails: i.external_ip if i.Place == "Australia"],0)
}
output "list" {
value = [for i in local.site24x7IPs.LocationDetails: i.external_ip if i.Place == "Australia"]
}
Outputs:
australia_ip_with_quotes = "103.91.166.0/24"
australia_ip_without_quotes = 103.91.166.0/24
list = [
"103.91.166.0/24",
]

Can I combine Json.Builder with JsonOutput in groovy? CSV to JSON

I have to parse csv file (with some modifications) to json in groovy.When I'm trying to execute this code i have a problem with spliting some values.
Content of csv file:
TestKey;Finished;user;status
RWS.PT.001;2020-07-20T23:01:21+02:00;admin;PASS;
RWS.PT.002;2020-07-20T23:02:21+02:00;admin;PASS;
my code in groovy:
import groovy.json.*
def builder = new groovy.json.JsonBuilder()
def root = builder {
testExecutionKey 'DEMO-303'
info (
user: 'admin')
tests 'rows':'ghgh','uuuuu'
}
print JsonOutput.prettyPrint(JsonOutput.toJson(root))
def csvfile = new File('C:/temp/raportTest.csv').readLines()
def keys = csvfile[0].split(';')
def rows = csvfile[1..-1].collect { line ->
def i = 0, vals = line.split(';')
keys.inject([:]) { map, key -> map << ["$key": vals[i++]] }
}
print JsonOutput.prettyPrint(JsonOutput.toJson(rows))
my target file should looks like this:
{
"testExecutionKey": "DEMO-303",
"info" : {
"user" : "admin"
},
"tests" : [
{
"testKey" : "RWS.PT.001",
"finished" : "2020-07-20T23:01:21+02:00",
"status" : "PASS"
},
{
"testKey" : "RWS.PT.002",
"finished" : "2020-07-20T23:01:21+02:00",
"status" : "PASS"
}
]
}
Now I have:
{
"testExecutionKey": "DEMO-303",
"info": {
"user": "admin"
},
"tests": [
{
"rows": "ghgh"
},
"uuuuu"
]
}[
{
"TestKey": "RWS.PT.001",
"Finished": "2020-07-20T23:01:21+02:00",
"user": "admin",
"status": "PASS"
},
{
"TestKey": "RWS.PT.002",
"Finished": "2020-07-20T23:02:21+02:00",
"user": "admin",
"status": "PASS"
}
]
How can I input code from def rows (from JsonOutput) into JsonBuilder (instead of "rows": "ghgh").
Please help!
You over-engineered it a bit. You actually don't have to combine anything, just use the JsonBuilder and some Groovy magic:
import groovy.json.*
def kindaFile = '''
TestKey;Finished;user;status
RWS.PT.001;2020-07-20T23:01:21+02:00;admin;PASS;
RWS.PT.002;2020-07-20T23:02:21+02:00;admin;PASS;
'''.trim()
def keys
def testList = []
//parse CSV
kindaFile.splitEachLine( /;/ ){ parts ->
if( !keys )
keys = parts
else{
def test = [:]
parts.eachWithIndex{ val, ix -> test[ keys[ ix ] ] = val }
testList << test
}
}
def builder = new JsonBuilder()
def root = builder {
testExecutionKey 'DEMO-303'
info user: 'admin'
tests testList
}
println JsonOutput.prettyPrint(JsonOutput.toJson(root))
prints
{
"testExecutionKey": "DEMO-303",
"info": {
"user": "admin"
},
"tests": [
{
"TestKey": "RWS.PT.001",
"Finished": "2020-07-20T23:01:21+02:00",
"user": "admin",
"status": "PASS"
},
{
"TestKey": "RWS.PT.002",
"Finished": "2020-07-20T23:02:21+02:00",
"user": "admin",
"status": "PASS"
}
]
}

how to print json array in jsonobject when we will get element of jsonarrray at runtime

ArrayList al = new ArrayList();
//al[0] and al[1] are the json objects.
def json = new JsonBuilder()
json {
type "rel12"
total k
xyz ""
shows al[0],al[1]
emails ""
}
println json.toPrettyString()
i dont want to do the the hardcoding like al[0]. al[1].
but i need the output like
{
"type": "rel12",
"total": 2,
"xyz": "",
"shows": [
{
"extension": "zip",
"updateTime": 1477521104511
},
{
"extension": "zip",
"updateTime": 1477521104623
}
],
"emails": ""
}