bellotto
bellotto

Reputation: 519

Parsing String to JSON in AWS Step Function's Map State

I'm facing an issue with parsing a "stringified JSON" in an AWS Step Function's Map state. My state machine first invokes a Lambda function that returns a JSON object. The output looks like this:

{
"requests": "{\"Data\":[{\"ID\":\"10001\",\"GroupID\":\"9999\"},{\"ID\":\"10002\",\"GroupID\":\"9999\"}]}"
}

When I call this lambda through an endpoint, it returns a normal JSON. However, when it appears in the output window inside the edit mode in the Step Function, it's a string. Then, my next step would be to iterate over the array. I have to filter by the key "Data" and there's the array. But in order to pass that as input for the next part (which is a map state), I have to be able to give an array.

Any suggestions or insights on handling this situation within the confines of AWS Step Functions would be greatly appreciated.

Upvotes: 3

Views: 8060

Answers (1)

cam
cam

Reputation: 5218

You can use the intrinsic function to transform the request output into JSON with the States.StringToJson function and use an OutputPath filter to pass the Data field to the map state.

https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-intrinsic-functions.html#asl-intrsc-func-json-manipulate

Something like the following (see String To Json step).

The input to the String To Json step is {"input": "{\"Data\":[1,2,3,4]}"}, output is [1,2,3,4].

{
  "Comment": "A description of my state machine",
  "StartAt": "Json To String",
  "States": {
    "Json To String": {
      "Type": "Pass",
      "Next": "String To Json",
      "Parameters": {
        "input.$": "States.JsonToString($.input)"
      }
    },
    "String To Json": {
      "Type": "Pass",
      "Next": "Map",
      "Parameters": {
        "input.$": "States.StringToJson($.input)"
      },
      "OutputPath": "$.input.Data"
    },
    "Map": {
      "Type": "Map",
      "ItemProcessor": {
        "ProcessorConfig": {
          "Mode": "INLINE"
        },
        "StartAt": "Pass (1)",
        "States": {
          "Pass (1)": {
            "Type": "Pass",
            "End": true
          }
        }
      },
      "End": true
    }
  }
}

With example input below, this passes 1,2,3,4 to the "pass" state using the map.

{
"input": { "Data": [1,2,3,4] }
}

Upvotes: 4

Related Questions