Home > front end >  Groovy script to compare 2 JSON array objects
Groovy script to compare 2 JSON array objects

Time:08-09

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)

CodePudding user response:

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