You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅用Amazon States Language获取Amazon Step Functions中数组长度

How to Get Array Length in Amazon Step Functions Using Only ASL (No External Services)

Nice question! You don't need Lambda or any external AWS services to calculate an array's length in Step Functions—Amazon States Language (ASL) has built-in intrinsic functions that let you do this directly within a Pass state (a state type designed for in-line data transformation).

Complete ASL State Machine Definition

Here's a ready-to-use state machine that takes your sample input and returns exactly the output you're looking for:

{
  "Comment": "Calculate length of SampleArray using ASL intrinsic functions",
  "StartAt": "CalculateArrayLength",
  "States": {
    "CalculateArrayLength": {
      "Type": "Pass",
      "Parameters": {
        "LengthOfSampleArray.$": "States.ArrayLength($.SampleArray)"
      },
      "End": true
    }
  }
}

How This Works

Let's break down the key components:

  • Pass State: This state runs entirely within Step Functions' runtime, no external calls required. It's purpose-built for shaping or transforming input data.
  • Parameters Field: We use this to construct our desired output structure. The .$ suffix tells Step Functions that the value is dynamically calculated, not static text.
  • States.ArrayLength(): This is ASL's native function for getting an array's length. We pass it the JSONPath to our target array ($.SampleArray) from the input.
  • End: true: Marks this as the final state in the workflow, so execution stops here and returns the constructed output.

Input/Output Example

Sample Input:

{ 
  "SampleField" : "SampleString", 
  "SampleField2" : "SampleString2", 
  "SampleArray": [ 
    { "Name": "Jack", "Age": 10 }, 
    { "Name": "John", "Age": 18 }, 
    { "Name": "Mary", "Age": 15 } 
  ] 
}

Resulting Output:

{ "LengthOfSampleArray": 3 }

Bonus: Retain Original Input + Add Length Field

If you ever want to keep the original input data while adding the length field, adjust the ResultPath to merge the calculated value into the input:

{
  "Comment": "Add array length to original input",
  "StartAt": "AddArrayLength",
  "States": {
    "AddArrayLength": {
      "Type": "Pass",
      "Parameters": {
        "LengthOfSampleArray.$": "States.ArrayLength($.SampleArray)"
      },
      "ResultPath": "$",
      "End": true
    }
  }
}

This will output the original input with the LengthOfSampleArray field added to the top level.

内容的提问来源于stack exchange,提问作者Prithvi Sreenivasan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:28:56