Search code examples
jsonamazon-web-servicesjsonpathaws-step-functions

AWS Step functions: how to append a key-value pair to the input json with jsonpath?


As per the doc of AWS Step Functions, you can use the JSON path syntax in the Parameters transformation to create a collection of key-value pairs that are passed as input. Given the following input:

{
  "comment": "Example for Parameters.",
  "product": {
    "details": {
       "color": "blue",
       "size": "small",
       "material": "cotton"
    },
    "availability": "in stock",
    "sku": "2317",
    "cost": "$23"
  }
}

I'd like to transform it this way:

{
  "foo": "My new value",
  "comment": "Example for Parameters.",
  "product": {
    "details": {
       "color": "blue",
       "size": "small",
       "material": "cotton"
    },
    "availability": "in stock",
    "sku": "2317",
    "cost": "$23"
  }
}

A way to do it can be the following:

{
  "foo": "My new value",
  "comment.$": "$.comment",
  "product.$": "$.product"      
}

Is there a way to obtain the same result with a kind of "apppend operation", without explicitly referencing the other parts of the JSON that aren't changed at all (i.e., comment.$ and product.$)?


Solution

  • GIVEN the Pass state:

    {
      "Comment": "Append a new key-value pair",
      "StartAt": "AppendFoo",
      "States": {
        "AppendFoo": {
          "Type": "Pass",
          "Result": "My new value",
          "ResultPath": "$.foo",
          "End": true
        }
      }
    }
    

    WHEN the OP input is passed,

    THEN the expected output is produced. The Result is inserted at ResultPath. Note that Result must be a literal value (no .$ substitutions allowed), but need not be a string. See the example in the docs.