比较2个JSON数组对象的Groovy脚本

cnjp1d6j  于 2022-11-01  发布在  其他
关注(0)|答案(1)|浏览(203)

我试图找到使用Groovy脚本比较两个JSON数组对象的最佳方法。

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

在obj2中找到obj1的值后,我需要返回如下所示的JSON输出,其中OrderNumber是关键标识符。

{
"ResultPO":
[
  {
    "OrderNumber": "12345_00001",
    "Location": "US",
    "Customer": "ABC"
  }
]
}

下面是我尝试使用JsonSlurper和findall的示例代码,但无法获得所需的结果。

def builder
   def filterJson
   filterJson = Obj2.findAll(){ it.OrderNumber.substring(0,4) == Obj1.OrderNumber.text()}
   builder = new JsonBuilder(filterJson)
mspsb9vt

mspsb9vt1#

试试这个:

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

相关问题