groovy 如何在JSON数组中为两个值建立索引?

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

我正在尝试查找两个匹配值的数组索引。下面是我的Groovy脚本,它为我提供了WhenWeighed的索引,并且可以正常工作。返回正确的索引。我遇到困难的部分是将OpSeq添加到索引条件中。
我想做的是找到WhenWeighed和OpSeq的索引。例如,我想找到WhenWeighed = BH和OpSeq = 30的索引。在我下面的JSON中,这应该是4。
有谁能解释一下您是如何在Groovy中实现这一点的吗?
使用的JSON:

{
  "BusinessUnit": "1111111",
  "WorkOrder": 1111111,
  "WeightEstimatesInq": [
    {
      "WhenWeighed": "BH",
      "WhenWeighedDesc": "Before Heading Weight",
      "TotalWeight": 900,
      "Weight": 12,
      "OpSeq": "10",
      "AdditionalNotes": " ",
      "TareWeight": " ",
      "Effective Date": "null"
    },
    {
      "WhenWeighed": "AH",
      "WhenWeighedDesc": "After Heading Weight",
      "TotalWeight": 987,
      "Weight": 900,
      "OpSeq": "10",
      "AdditionalNotes": "Weighed Bin 10 5/17/2022",
      "TareWeight": "87",
      "Effective Date": "null"
    },
    {
      "WhenWeighed": "BO",
      "WhenWeighedDesc": "Before OSP Weight",
      "TotalWeight": 900,
      "Weight": 9,
      "OpSeq": "50",
      "AdditionalNotes": " ",
      "TareWeight": " ",
      "Effective Date": "null"
    },
    {
      "WhenWeighed": "AO",
      "WhenWeighedDesc": "After OSP Weight",
      "TotalWeight": 1000,
      "Weight": 750,
      "OpSeq": "50",
      "AdditionalNotes": " ",
      "TareWeight": "150",
      "Effective Date": "null"
    },
    {
      "WhenWeighed": "BH",
      "WhenWeighedDesc": "Before Heading Weight",
      "TotalWeight": 720,
      "Weight": 700,
      "OpSeq": "30",
      "AdditionalNotes": "Weighed Bin 30 5/17/2022",
      "TareWeight": "20",
      "Effective Date": "null"
    }
  ],
  "status": "SUCCESS",
  "startTimestamp": "2022-05-17T12:27:49.302-0400",
  "endTimestamp": "2022-05-17T12:27:50.279-0400",
  "serverExecutionSeconds": 0.977
}

使用的Groovy:

// Read Input Values
  String aWhenWeighedUDC = aInputMap.WhenWeighedUDC ?: " "
  String aInputJson = aInputMap.InputJson ?: "{}"

  // Initialize Output Values
  def error = " "
  def rowNumber = 0
  def lastRowNumber = 1
  // Parse JSON
  def json = new JsonSlurper().parseText( aInputJson )

  // Determine Row Numbers
  def rowset = json?.WeightEstimatesInq
  if ( rowset ) {
    rowNumber = rowset*.WhenWeighed.indexOf( aWhenWeighedUDC ) + 1
    lastRowNumber = rowset.size()
  }
nfs0ujit

nfs0ujit1#

如果你知道WeightEstimatesInq总是项目列表的键,你可以这样做:

json["WeightEstimatesInq"].findIndexOf {
   it["WhenWeighed"] == "BH" && it["OpSeq"] == "30"
}

这将生成4。您可以通过&&添加更多条件。
请注意,如果没有符合条件的项目,则可能会传回-1

相关问题