Search code examples
amazon-web-servicesaws-cdkaws-step-functions

In a Step Function, how do I convert an array of scalars into an array of dictionaries?


Input of the step - How to Modify the input of the step in a step function from this:

{
    "A": "X",
    "B": "Y",
    "C": [
        "Z1",
        "Z2",
        "Z3"
    ]
}

and convert into this

{
    "A": "X",
    "B": "Y",
    "C": [
        {
            "Z": "Z1"
        },
        {
            "Z": "Z2"
        },
        {
            "Z": "Z3"
        }
    ]
}

using ASL or C# CDK. I tried to convert an array of strings to an array of elements using:

        "Modify Input": {
            "Type": "Pass",
            "Parameters": {
                "A": "$.A",
                "B": "$.B",
                "C": [
                    {
                        "Z": "States.array($.C)"
                    }
                ]
            }

Solution

  • Append .$ to the key name if the value is a JsonPath substitution. Without it, Step Functions treats the value as a string literal. Use the States.ArrayGetItem intrinsic function to pick items at an index:

    {
      "A.$": "$.A",
      "B.$": "$.B",
      "C": [
        { "Z.$": "States.ArrayGetItem($.C,0)" },
        { "Z.$": "States.ArrayGetItem($.C,1)" },
        { "Z.$": "States.ArrayGetItem($.C,2)" }
      ]
    }
    

    The CDK accepts these literal values. It also provides the optional JsonPath class, which exposes methods for the intrinsic classes and lets you omit the .$ from key names. The CDK emits the same State Machine definition output either way.