diff --git a/sim/executor/loops.ts b/sim/executor/loops.ts index 29c68193e9..1c326c201d 100644 --- a/sim/executor/loops.ts +++ b/sim/executor/loops.ts @@ -247,7 +247,18 @@ export class LoopManager { return []; } - // Simple expression evaluation using Function constructor + // First check if it's valid JSON (array or object) + if (trimmedExpression.startsWith('[') || trimmedExpression.startsWith('{')) { + try { + // Try to parse as JSON first + return JSON.parse(trimmedExpression); + } catch (jsonError) { + console.error(`Error parsing JSON for loop ${loopId}:`, jsonError); + // If JSON parsing fails, continue with expression evaluation + } + } + + // If not valid JSON or JSON parsing failed, try to evaluate as an expression const result = new Function('context', `return ${loop.forEachItems}`)(context); // If the result is an array or object, return it diff --git a/sim/executor/resolver.ts b/sim/executor/resolver.ts index 83c67cf4a2..5aad7e4759 100644 --- a/sim/executor/resolver.ts +++ b/sim/executor/resolver.ts @@ -626,12 +626,18 @@ export class InputResolver { if (typeof loop.forEachItems === 'string') { try { // Check if it's valid JSON - if (loop.forEachItems.trim().startsWith('[') || loop.forEachItems.trim().startsWith('{')) { - return JSON.parse(loop.forEachItems); + const trimmedExpression = loop.forEachItems.trim(); + if (trimmedExpression.startsWith('[') || trimmedExpression.startsWith('{')) { + try { + // Try to parse as JSON first + return JSON.parse(trimmedExpression); + } catch (jsonError) { + console.error(`Error parsing JSON for loop:`, jsonError); + // If JSON parsing fails, continue with expression evaluation + } } - // Otherwise, try to evaluate it as an expression - const trimmedExpression = loop.forEachItems.trim(); + // If not valid JSON or JSON parsing failed, try to evaluate as an expression if (trimmedExpression && !trimmedExpression.startsWith('//')) { const result = new Function('context', `return ${loop.forEachItems}`)(context); if (Array.isArray(result) || (typeof result === 'object' && result !== null)) { diff --git a/sim/stores/workflows/workflow/store.ts b/sim/stores/workflows/workflow/store.ts index 51a743bb41..9c290de31a 100644 --- a/sim/stores/workflows/workflow/store.ts +++ b/sim/stores/workflows/workflow/store.ts @@ -572,13 +572,14 @@ export const useWorkflowStore = create()( ) { try { // First try to parse to validate it's valid JSON - JSON.parse(items); + const parsed = JSON.parse(items); // If parsing succeeds, store the original string to preserve formatting // This way we keep the user's exact formatting (spacing, line breaks, etc.) parsedItems = items; } catch (e) { - // If parsing fails, keep it as a string + // If parsing fails, keep it as a string expression + console.error('Invalid JSON format for forEach items:', e); parsedItems = items; } }