AWS Step Function:函数 .length() 在选择状态的变量字段中返回错误

AWS Step Function: Function .length() returned error in variable field in Choice state

我在 AWS Step Function 中有一个 Choice 状态,它会比较输入的数组长度并决定进入下一个状态。

但是,length() 函数获取数组的长度时返回错误:

{
"error": "States.Runtime",
"cause": "An error occurred while executing the state 'CheckItemsCountState' (entered at the event id #18). Invalid path '$.Metadata[2].Items.length()': The choice state's condition path references an invalid value."

}

Choice状态定义如下:

     "CheckItemsCountState":{  
         "Type": "Choice",
         "InputPath": "$",
         "OutputPath": "$",
         "Default": "NoItemsState",
         "Choices":[  
            {  
               "Variable": "$.Metadata[2].Items.length()",
               "NumericGreaterThan": 0,
               "Next": "ProcessState"
            }
         ]
      },

状态与returns一个JSON的其他状态相连。 JSON如下:

{
  "Metadata": [
    {
      "foo": "name"
    },
    {
      "Status": "COMPLETED"
    },
    {
      "Items": []
    }
  ]
}

所以我试图在Metadata[2]中获取Items的长度,如果该值大于0则进行比较。

我已尝试验证此 website 中的 JsonPath $.Metadata[2].Items.length() 并且它 returns 0.

我不确定我是否遗漏了什么。我在 AWS Step Function 的文档或示例中找不到有关在 jsonpath 中使用函数的任何信息。

如有任何帮助,我将不胜感激。谢谢!

Step Functions 不允许您使用函数获取值。来自 Choice Rules documentation:

For each of these operators, the corresponding value must be of the appropriate type: string, number, Boolean, or timestamp.

要执行您要求的操作,您需要在上一个函数中获取数组长度,然后 return 将其作为输出的一部分。

{
  "Metadata": [
    {
      "foo": "name"
    },
    {
      "Status": "COMPLETED"
    },
    {
      "Items": [],
      "ItemsCount": 0
    }
  ]
}

然后在Step Function Choice步骤:

"CheckItemsCountState":{  
    "Type": "Choice",
    "InputPath": "$",
    "OutputPath": "$",
    "Default": "NoItemsState",
    "Choices":[  
        {  
            "Variable": "$.Metadata[2].ItemsCount",
            "NumericGreaterThan": 0,
            "Next": "ProcessState"
        }
    ]
},

一种可能的方法是检查零索引,如果您只想检查它是一个非空数组。

你可以这样做

"CheckItemsCountState":{  
     "Type": "Choice",
     "InputPath": "$",
     "OutputPath": "$",
     "Default": "NoItemsState",
     "Choices":[
       {
         "And": [
           {
            "Variable": "$.Metadata[2].Items",
            "IsPresent": true
           },
           {
             "Variable": "$.Metadata[2].Items[0]",
             "IsPresent": true
           }
         ],
        "Next": "ProcessState"
       }
     ]
  }

另一种方法是接受的答案中提到的,在上一个函数中设置计数。