ModelWorks logoModelWorks
JSON TransformArray

replaceMatching

Replace array elements that match a JMESPath condition

replaceMatching

Walks the array and replaces every element whose condition (JMESPath, evaluated against item/@) resolves to true with the next value drawn from with. The mode controls whether all matches are replaced or just the first.

Options

OptionTypeRequiredDefaultDescription
conditionstringYesJMESPath boolean expression. item and @ refer to the current element.
withanyYesReplacement value (or array of values, drawn one per match). Selectors resolved first.
modestringNo"all""all" to replace every match; "first" to replace only the first.

Example

Input

JSON
[
  { "role": "system",    "content": "Old prompt" },
  { "role": "user",      "content": "Hi" },
  { "role": "system",    "content": "Another stale prompt" }
]

Operation

JSON
{
  "type": "replaceMatching",
  "options": {
    "condition": "item.role == `system`",
    "with": [
      { "role": "system", "content": "You are a helpful assistant." }
    ],
    "mode": "first"
  }
}

Output

JSON
[
  { "role": "system", "content": "You are a helpful assistant." },
  { "role": "user",   "content": "Hi" },
  { "role": "system", "content": "Another stale prompt" }
]

In a Circuit Step

JSON
{
  "name": "swap_first_system_prompt",
  "description": "Replace only the first system message with a fresh prompt",
  "function": "circuit.core.transform.json",
  "input": {
    "source": "${{ messages }}",
    "operations": [
      {
        "type": "replaceMatching",
        "options": {
          "condition": "item.role == `system`",
          "with": [
            { "role": "system", "content": "${{ prompts.system_prompt }}" }
          ],
          "mode": "first"
        }
      }
    ]
  },
  "outputs": [
    {
      "name": "patched_messages",
      "description": "Messages with the first system prompt swapped",
      "value": "${{ swap_first_system_prompt.output.transformed_result }}"
    }
  ]
}

Notes & gotchas

  • Errors with replaceMatching: expected array if the input is not an array.
  • with is selector-evaluated. If the resolved value is an array, replacements are drawn from it sequentially: first match takes the first replacement, second match the second, etc. Once exhausted, further matches are dropped from the output (rather than left as-is) when running in mode: "all".
  • A scalar with is wrapped into a single-element list, so mode: "all" with a scalar effectively replaces only the first match.
  • Use mode: "first" for the canonical "swap the first system prompt" pattern.
  • For simple value-equality matching, filter + unshift is often clearer than replaceMatching.
On this page

On this page