Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat: implement Step Functions intrinsic functions (States.StringToJson, States.JsonMerge, States.Format) (#167)

Jay Janssen674032fd4926
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9afd2b0b..a19cc3b1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,16 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [Unreleased]
+
+### Added
+- **Step Functions intrinsic functions** — `States.StringToJson`, `States.JsonMerge`, `States.Format` now work in `Parameters` and `ResultSelector`. Supports nested intrinsic calls. Enables real-world ASL definitions that use string interpolation and JSON manipulation
+
+### Tests
+- 4 new tests: `States.StringToJson`, `States.JsonMerge`, `States.Format`, nested intrinsics
+
+---
+
## [1.1.45] — 2026-04-07
### Added
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index 67590a42..b357311e 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -1665,6 +1665,131 @@ def _resolve_path(path, data):
return cur
+def _parse_intrinsic_args(s, pos):
+ """Recursive descent parser for intrinsic function arguments.
+
+ Returns (list_of_args, next_pos) where next_pos is after the closing ')'.
+ """
+ args = []
+ pos = _skip_ws(s, pos)
+ if pos < len(s) and s[pos] == ")":
+ return args, pos + 1
+
+ while pos < len(s):
+ pos = _skip_ws(s, pos)
+ if pos >= len(s):
+ break
+
+ ch = s[pos]
+
+ if s[pos:].startswith("States."):
+ arg, pos = _parse_intrinsic_call(s, pos)
+ args.append(arg)
+ elif ch == "'":
+ end = s.index("'", pos + 1)
+ args.append(("str", s[pos + 1 : end]))
+ pos = end + 1
+ elif ch == "$":
+ end = pos
+ while end < len(s) and s[end] not in (",", ")"):
+ end += 1
+ args.append(("path", s[pos:end].strip()))
+ pos = end
+ elif ch in "0123456789-":
+ end = pos + 1
+ while end < len(s) and s[end] not in (",", ")"):
+ end += 1
+ tok = s[pos:end].strip()
+ if "." in tok:
+ args.append(("num", float(tok)))
+ else:
+ args.append(("num", int(tok)))
+ pos = end
+ elif s[pos : pos + 4] == "true":
+ args.append(("bool", True))
+ pos += 4
+ elif s[pos : pos + 5] == "false":
+ args.append(("bool", False))
+ pos += 5
+ elif s[pos : pos + 4] == "null":
+ args.append(("null", None))
+ pos += 4
+ else:
+ pos += 1
+ continue
+
+ pos = _skip_ws(s, pos)
+ if pos < len(s) and s[pos] == ",":
+ pos += 1
+ elif pos < len(s) and s[pos] == ")":
+ return args, pos + 1
+
+ return args, pos
+
+
+def _skip_ws(s, pos):
+ while pos < len(s) and s[pos] in " \t\n\r":
+ pos += 1
+ return pos
+
+
+def _parse_intrinsic_call(s, pos):
+ """Parse a States.Xxx(...) call starting at pos. Returns (('call', name, args), next_pos)."""
+ paren = s.index("(", pos)
+ name = s[pos:paren].strip()
+ args, end = _parse_intrinsic_args(s, paren + 1)
+ return ("call", name, args), end
+
+
+def _eval_intrinsic_arg(arg, data, ctx):
+ """Evaluate a single parsed argument node."""
+ kind = arg[0]
+ if kind == "str":
+ return arg[1]
+ elif kind == "num" or kind == "bool" or kind == "null":
+ return arg[1]
+ elif kind == "path":
+ path = arg[1]
+ if path.startswith("$$."):
+ return _resolve_ctx_path(path, ctx or {})
+ return _resolve_path(path, data)
+ elif kind == "call":
+ return _exec_intrinsic(arg, data, ctx)
+ return None
+
+
+def _exec_intrinsic(node, data, ctx):
+ """Execute a parsed intrinsic call node ('call', name, args)."""
+ _, name, raw_args = node
+ args = [_eval_intrinsic_arg(a, data, ctx) for a in raw_args]
+
+ if name == "States.StringToJson":
+ return json.loads(args[0])
+ elif name == "States.JsonMerge":
+ merged = {}
+ merged.update(args[0])
+ merged.update(args[1])
+ return merged
+ elif name == "States.Format":
+ template = args[0]
+ parts = template.split("{}")
+ result_parts = []
+ for i, part in enumerate(parts):
+ result_parts.append(part)
+ if i < len(parts) - 1 and i < len(args) - 1:
+ val = args[i + 1]
+ result_parts.append(str(val) if not isinstance(val, str) else val)
+ return "".join(result_parts)
+
+ raise ValueError(f"Unsupported intrinsic function: {name}")
+
+
+def _evaluate_intrinsic(expression, data, ctx):
+ """Parse and evaluate a States.* intrinsic function expression."""
+ node, _ = _parse_intrinsic_call(expression, 0)
+ return _exec_intrinsic(node, data, ctx)
+
+
def _resolve_params_obj(template, data, ctx=None):
if not isinstance(template, dict):
return template
@@ -1673,7 +1798,9 @@ def _resolve_params_obj(template, data, ctx=None):
if key.endswith(".$"):
real_key = key[:-2]
if isinstance(value, str):
- if value.startswith("$$."):
+ if value.startswith("States."):
+ result[real_key] = _evaluate_intrinsic(value, data, ctx)
+ elif value.startswith("$$."):
result[real_key] = _resolve_ctx_path(value, ctx or {})
else:
result[real_key] = _resolve_path(value, data)
diff --git a/tests/test_services.py b/tests/test_services.py
index d84bf8dc..3ba7b934 100644
--- a/tests/test_services.py
+++ b/tests/test_services.py
@@ -4293,6 +4293,118 @@ def test_sfn_tags_v2(sfn):
assert any(t["key"] == "env" for t in tags3)
+def test_sfn_intrinsic_string_to_json(sfn, sfn_sync):
+ """States.StringToJson parses a JSON string into structured data."""
+ definition = json.dumps({
+ "StartAt": "Parse",
+ "States": {
+ "Parse": {
+ "Type": "Pass",
+ "Parameters": {
+ "parsed.$": "States.StringToJson($.raw)"
+ },
+ "End": True,
+ }
+ },
+ })
+ sm = sfn.create_state_machine(
+ name="sfn-intrinsic-s2j",
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ resp = sfn_sync.start_sync_execution(
+ stateMachineArn=sm["stateMachineArn"],
+ input=json.dumps({"raw": '{"a":1,"b":2}'}),
+ )
+ assert resp["status"] == "SUCCEEDED"
+ output = json.loads(resp["output"])
+ assert output["parsed"] == {"a": 1, "b": 2}
+
+
+def test_sfn_intrinsic_json_merge(sfn, sfn_sync):
+ """States.JsonMerge shallow-merges two objects."""
+ definition = json.dumps({
+ "StartAt": "Merge",
+ "States": {
+ "Merge": {
+ "Type": "Pass",
+ "Parameters": {
+ "merged.$": "States.JsonMerge($.obj1, $.obj2, false)"
+ },
+ "End": True,
+ }
+ },
+ })
+ sm = sfn.create_state_machine(
+ name="sfn-intrinsic-jm",
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ resp = sfn_sync.start_sync_execution(
+ stateMachineArn=sm["stateMachineArn"],
+ input=json.dumps({"obj1": {"a": 1, "c": 3}, "obj2": {"b": 2, "c": 99}}),
+ )
+ assert resp["status"] == "SUCCEEDED"
+ output = json.loads(resp["output"])
+ assert output["merged"] == {"a": 1, "b": 2, "c": 99}
+
+
+def test_sfn_intrinsic_format(sfn, sfn_sync):
+ """States.Format interpolates arguments into a template string."""
+ definition = json.dumps({
+ "StartAt": "Fmt",
+ "States": {
+ "Fmt": {
+ "Type": "Pass",
+ "Parameters": {
+ "greeting.$": "States.Format('Hello {} from {}', $.name, $.city)"
+ },
+ "End": True,
+ }
+ },
+ })
+ sm = sfn.create_state_machine(
+ name="sfn-intrinsic-fmt",
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ resp = sfn_sync.start_sync_execution(
+ stateMachineArn=sm["stateMachineArn"],
+ input=json.dumps({"name": "Jay", "city": "SF"}),
+ )
+ assert resp["status"] == "SUCCEEDED"
+ output = json.loads(resp["output"])
+ assert output["greeting"] == "Hello Jay from SF"
+
+
+def test_sfn_intrinsic_nested(sfn, sfn_sync):
+ """Nested intrinsic: States.StringToJson(States.Format(...))"""
+ definition = json.dumps({
+ "StartAt": "Nested",
+ "States": {
+ "Nested": {
+ "Type": "Pass",
+ "Parameters": {
+ "result.$": "States.StringToJson(States.Format('{\"key\":\"{}\"}', $.val))"
+ },
+ "End": True,
+ }
+ },
+ })
+ sm = sfn.create_state_machine(
+ name="sfn-intrinsic-nested",
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ resp = sfn_sync.start_sync_execution(
+ stateMachineArn=sm["stateMachineArn"],
+ input=json.dumps({"val": "hello"}),
+ )
+ assert resp["status"] == "SUCCEEDED"
+ output = json.loads(resp["output"])
+ assert output["result"] == {"key": "hello"}
+
+
# ===================================================================
# ECS — comprehensive tests
# ===================================================================