如何仅用Amazon States Language获取Amazon Step Functions中数组长度
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:
PassState: This state runs entirely within Step Functions' runtime, no external calls required. It's purpose-built for shaping or transforming input data.ParametersField: 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

