{"secureTokens":{"secrets":[],"connections":[],"aiModels":[]},"isPublished":true,"isTriggerTypeChanged":false,"id":"5632455367196672","name":"Dynamic collection body builder","description":"","rootContainer":{"id":"ox0pk5iwkmtd6gnul","type":"container","steps":[{"actionTypeId":"parsejson-v1","errorHandling":{"retries":[],"errorAction":0},"id":"6q2ulzpdamtdin677","name":"Convert JSON to Object","displayName":"Sample collection (replace with your own)","settings":{"input":[{"type":"text","value":"[\n  {\n    \"email\": \"ann@company.com\"\n  },\n  {\n    \"email\": \"bob@company.com\"\n  },\n  {\n    \"email\": \"carol@company.com\"\n  }\n]"}],"schema":"{\n    \"type\": \"array\",\n    \"items\": {\n        \"type\": \"object\",\n        \"properties\": {\n            \"email\": {\n                \"type\": \"string\",\n                \"title\": \"Email\"\n            }\n        }\n    },\n    \"$schema\": \"http://json-schema.org/draft-04/schema\"\n}"},"type":"action"},{"id":"qkjuyykfnmtdodv5h","name":"Set Variable","displayName":"1. Set your body template","settings":{"variables":[{"name":"1","displayName":"JSON Body","valueType":"string","isArray":false,"operation":1,"value":[{"type":"text","value":"{\n  \"source\": \"zenphi\",\n  \"users\": {{users}}\n}"}],"error":null}]},"type":"setVariable"},{"container":{"id":"ep3apfwaimtd6qia5","type":"container","steps":[{"actionTypeId":"script-v2","errorHandling":{"retries":[],"errorAction":0},"id":"zsntt0l11mtd6gya5","name":"Execute Script","displayName":"3. Add this item to the body","settings":{"parameters":[{"name":"placeholder","dataType":"string","value":{"stringValue":[{"type":"text","value":"{{users}}"}]}},{"name":"newItem","dataType":"string","value":{"stringValue":[{"type":"text","value":"{ \"email\": \""}]}},{"name":"body","dataType":"string","value":{"stringValue":[{"type":"ref","value":{"referenceType":"flowVariable","displayName":"Variable.JSON Body","dataType":"string","outputName":"1","name":"1","isProjected":false,"path":"$.1","iconSrc":"assets/img/designer/variable.svg","error":false}}]}}],"script":"// Appends a new item into a JSON body or template at a targeted placeholder array\nexport default function run() {\n  const SENTINEL = '__ZP_ANCHOR__';\n\n  function clean(v: unknown): string {\n    return String(v === null || v === undefined ? '' : v)\n      .replace(/[\\u200B-\\u200F\\u202A-\\u202E\\uFEFF\\u00A0]/g, ' ')\n      .trim();\n  }\n\n  function parseJson(v: unknown): any {\n    if (!v) return null;\n    if (typeof v === 'object') return v;\n    let s = clean(v);\n    if (!s || s === '[object Object]' || s === 'null' || s === 'undefined') return null;\n    for (let i = 0; i < 2; i++) {\n      let p: any;\n      try {\n        p = JSON.parse(s);\n      } catch {\n        return null;\n      }\n      if (typeof p === 'string') {\n        s = p;\n        continue;\n      }\n      return p;\n    }\n    return null;\n  }\n\n  function bare(n: unknown): string {\n    return clean(n).replace(/^\\{\\{\\s*/, '').replace(/\\s*\\}\\}$/, '');\n  }\n\n  function expandTemplate(tpl: string): { body: any; paths: Record<string, (string | number)[]> } | null {\n    const s = String(tpl).replace(\n      /\"\\{\\{\\s*([A-Za-z0-9_.\\-]+)\\s*\\}\\}\"|\\{\\{\\s*([A-Za-z0-9_.\\-]+)\\s*\\}\\}/g,\n      (_m, quoted, plain) => '[\"' + SENTINEL + (quoted || plain) + '\"]'\n    );\n\n    const obj = parseJson(s);\n    if (!obj) return null;\n\n    const paths: Record<string, (string | number)[]> = {};\n    function walk(node: any, path: (string | number)[]) {\n      if (Array.isArray(node)) {\n        if (node.length === 1 && typeof node[0] === 'string' && node[0].indexOf(SENTINEL) === 0) {\n          paths[node[0].slice(SENTINEL.length)] = path.slice();\n          node.length = 0;\n          return;\n        }\n        for (let i = 0; i < node.length; i++) walk(node[i], path.concat(i));\n      } else if (node && typeof node === 'object') {\n        for (const k of Object.keys(node)) {\n          walk(node[k], path.concat(k));\n        }\n      }\n    }\n    walk(obj, []);\n\n    return { body: obj, paths };\n  }\n\n  function allArrays(root: any): (string | number)[][] {\n    const hits: (string | number)[][] = [];\n    function walk(node: any, p: (string | number)[]) {\n      if (Array.isArray(node)) {\n        hits.push(p.slice());\n        for (let i = 0; i < node.length; i++) walk(node[i], p.concat(i));\n      } else if (node && typeof node === 'object') {\n        for (const k of Object.keys(node)) {\n          walk(node[k], p.concat(k));\n        }\n      }\n    }\n    walk(root, []);\n    return hits;\n  }\n\n  function getByPath(root: any, path: (string | number)[]): any {\n    let cur = root;\n    for (let i = 0; i < path.length; i++) {\n      if (cur === null || typeof cur !== 'object') return undefined;\n      cur = cur[path[i]];\n    }\n    return cur;\n  }\n\n  function findByName(root: any, name: string): (string | number)[][] {\n    const hits: (string | number)[][] = [];\n    function walk(node: any, p: (string | number)[]) {\n      if (Array.isArray(node)) {\n        for (let i = 0; i < node.length; i++) walk(node[i], p.concat(i));\n      } else if (node && typeof node === 'object') {\n        for (const k of Object.keys(node)) {\n          if (k === name && Array.isArray(node[k])) hits.push(p.concat(k));\n          walk(node[k], p.concat(k));\n        }\n      }\n    }\n    walk(root, []);\n    return hits;\n  }\n\n  function signature(o: any): string {\n    if (!o || typeof o !== 'object' || Array.isArray(o)) return '';\n    return Object.keys(o).sort().join('|');\n  }\n\n  function findByStructure(root: any, item: any): { path: (string | number)[] | null; reason: string } {\n    const sig = signature(item);\n    const hits: { path: (string | number)[]; score: number }[] = [];\n    function walk(node: any, path: (string | number)[]) {\n      if (Array.isArray(node)) {\n        let score = 0;\n        for (let i = 0; i < node.length; i++) {\n          const s = signature(node[i]);\n          if (!s) continue;\n          if (s === sig) {\n            score += 2;\n          } else {\n            const a = s.split('|');\n            const b = sig.split('|');\n            let shared = 0;\n            for (let j = 0; j < a.length; j++) if (b.indexOf(a[j]) !== -1) shared++;\n            if (shared && shared >= Math.min(a.length, b.length) * 0.6) score += 1;\n          }\n        }\n        if (score > 0) hits.push({ path: path.slice(), score });\n        for (let x = 0; x < node.length; x++) walk(node[x], path.concat(x));\n      } else if (node && typeof node === 'object') {\n        for (const k of Object.keys(node)) {\n          walk(node[k], path.concat(k));\n        }\n      }\n    }\n    walk(root, []);\n\n    if (!hits.length) return { path: null, reason: 'no array matches the newItem structure' };\n    hits.sort((a, b) => b.score - a.score);\n    if (hits.length > 1 && hits[0].score === hits[1].score) {\n      return { path: null, reason: 'ambiguous: ' + hits.length + ' arrays match equally well' };\n    }\n    return { path: hits[0].path, reason: '' };\n  }\n\n  function fail(bodyJson: string, msg: string) {\n    return { bodyJson, itemCount: 0, appended: false, matchedBy: '', targetPath: '', error: msg };\n  }\n\n  const name = bare(parameters.placeholder);\n  const newItem = parseJson(parameters.newItem);\n  const raw = parameters.body;\n\n  if (!newItem || typeof newItem !== 'object' || Array.isArray(newItem)) {\n    return fail(clean(raw), 'newItem is not a JSON object');\n  }\n  if (raw === undefined || raw === null || clean(raw) === '') {\n    return fail('', 'body is empty - map the template on the first iteration');\n  }\n\n  const isTemplate = typeof raw === 'string' && /\\{\\{\\s*[A-Za-z0-9_.\\-]+\\s*\\}\\}/.test(raw);\n  const expanded = isTemplate ? expandTemplate(raw) : null;\n  const body = isTemplate ? (expanded ? expanded.body : null) : parseJson(raw);\n  const tplPaths = expanded && expanded.paths ? expanded.paths : {};\n  let matchedBy = '';\n\n  if (!body || typeof body !== 'object') {\n    return fail('', isTemplate ? 'template is not valid JSON once placeholders are expanded' : 'body is not valid JSON');\n  }\n\n  let path: (string | number)[] | null = null;\n\n  if (name && tplPaths[name]) {\n    path = tplPaths[name];\n    matchedBy = 'template';\n  }\n\n  if (!path && name) {\n    const named = findByName(body, name);\n    if (named.length === 1) {\n      path = named[0];\n      matchedBy = 'key-name';\n    } else if (named.length > 1) {\n      return fail(JSON.stringify(body), 'key \"' + name + '\" appears ' + named.length + ' times - rename it');\n    }\n  }\n\n  if (!path) {\n    const arrays = allArrays(body);\n    if (arrays.length === 1) {\n      path = arrays[0];\n      matchedBy = 'only-array';\n    }\n  }\n\n  if (!path) {\n    const f = findByStructure(body, newItem);\n    if (!f.path) {\n      const keys: string[] = [];\n      for (const kk of Object.keys(body)) {\n        if (Array.isArray(body[kk])) keys.push(kk);\n      }\n      return fail(\n        JSON.stringify(body),\n        'placeholder \"' + name + '\" not found. ' + f.reason +\n          (keys.length ? '. Arrays in the body: ' + keys.join(', ') + ' - rename the placeholder to match one of them' : '')\n      );\n    }\n    path = f.path;\n    matchedBy = 'structure';\n  }\n\n  const target = getByPath(body, path);\n  if (!Array.isArray(target)) return fail(JSON.stringify(body), 'resolved path is not an array');\n\n  target.push(newItem);\n\n  return {\n    bodyJson: JSON.stringify(body),\n    itemCount: target.length,\n    appended: true,\n    matchedBy,\n    targetPath: path.join('.'),\n    error: ''\n  };\n}","exportSchema":"{\n    \"$schema\": \"http://json-schema.org/draft-04/schema\",\n    \"type\": \"object\",\n    \"properties\": {\n        \"default\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"bodyJson\": {\n                    \"type\": \"string\",\n                    \"title\": \"Body JSON\"\n                },\n                \"itemCount\": {\n                    \"type\": \"number\",\n                    \"title\": \"Item Count\"\n                },\n                \"appended\": {\n                    \"type\": \"boolean\",\n                    \"title\": \"Appended\"\n                },\n                \"matchedBy\": {\n                    \"type\": \"string\",\n                    \"title\": \"Matched By\"\n                },\n                \"targetPath\": {\n                    \"type\": \"string\",\n                    \"title\": \"Target Path\"\n                },\n                \"error\": {\n                    \"type\": \"string\",\n                    \"title\": \"Error\"\n                }\n            },\n            \"title\": \"Default\"\n        }\n    }\n}","scriptError":false},"type":"action"},{"id":"3yv8d289wmtd6l87j","name":"Set Variable","displayName":"4. Save the updated body","settings":{"variables":[{"name":"1","displayName":"JSON Body","valueType":"string","isArray":false,"operation":1,"value":[{"type":"ref","value":{"referenceType":"stepParam","displayName":"3. Add this item to the body.Exports.Default.Body JSON","flowStepId":"zsntt0l11mtd6gya5","dataType":"string","outputName":"exports.default.bodyJson","isProjected":false,"path":".exports.default.bodyJson","possibleNull":false,"iconSrc":"assets/img/designer/actions/script-v2.svg","error":false}}],"error":null}]},"type":"setVariable"}],"label":"Loop"},"id":"5vchozg4jmtd6qia5","name":"Foreach Loop","displayName":"2. Loop through your collection","settings":{"collection":[{"type":"ref","value":{"referenceType":"stepParam","displayName":"Sample collection (replace with your own).Result.Email","flowStepId":"6q2ulzpdamtdin677","dataType":"string","outputName":"result.email","isProjected":true,"path":"$.result[*].email","possibleNull":false,"iconSrc":"assets/img/designer/actions/parsejson-v1.svg","error":false}}]},"type":"foreach"},{"actionTypeId":"logtohistory-v1","errorHandling":{"retries":[],"errorAction":0},"id":"fg444c04smtd6mliw","name":"Log to History","displayName":"Final JSON body (for testing)","settings":{"message":[{"type":"ref","value":{"referenceType":"flowVariable","displayName":"Variable.JSON Body","dataType":"string","outputName":"1","name":"1","isProjected":false,"path":"$.1","iconSrc":"assets/img/designer/variable.svg","error":false}}]},"type":"action"},{"actionTypeId":"utilityhttprequest-v1","errorHandling":{"retries":[],"errorAction":0},"id":"yh5o6gm8kmtdfa3x9","name":"Make HTTP Request","displayName":"5. Send one request with everything","settings":{"requestMethod":"post","bodyType":"text","authorizationType":"noAuth","fileContentType":null,"fileName":null,"body":[{"type":"ref","value":{"referenceType":"flowVariable","displayName":"Variable.JSON Body","dataType":"string","outputName":"1","name":"1","isProjected":false,"path":"$.1","iconSrc":"assets/img/designer/variable.svg","error":false}}],"payload":null,"formData":null,"urlencoded":null,"contentType":null},"type":"action"}],"label":null,"showLabel":false},"variables":[{"name":"1","displayName":"JSON Body","value":"","valueType":"string","isArray":false,"hasSchema":true,"objectSchema":null,"properties":null,"includeInOutput":null}],"triggers":[{"id":null,"name":"On Demand Flow","triggerType":"manualv1","triggerTypeName":"On Demand Flow","connectionId":null,"parameters":[],"configuration":null,"hasFilter":false,"filter":null}],"startParameters":[],"parameterMapping":[],"version":"1.7","isDraft":true,"isPrivate":true,"tags":[],"metadata":[],"publishedMetadata":[],"flowMetadata":{},"notes":[{"id":"n1sample","addedByName":"","addedByPicture":"","addedDate":"2026-08-29T16:00:00Z","stepId":"6q2ulzpdamtdin677","comment":"Just sample data so the flow runs out of the box. Replace this action with wherever your real collection comes from: a Google Sheet, a table, a list of users, invoice lines, anything.","displayName":"Sample collection (replace with your own)","iconSrc":"assets/img/designer/actions/parsejson-v1.svg"},{"id":"n2setbody","addedByName":"","addedByPicture":"","addedDate":"2026-08-29T16:00:00Z","stepId":"qkjuyykfnmtdodv5h","comment":"Put your COMPLETE body here, exactly as the API expects it, including every fixed field. Where a dynamic list should go, write a placeholder in double curly braces. One rule: name the placeholder exactly like the key it fills, so \"users\" is filled by {{users}}. Need two dynamic lists? Add a second placeholder here and run a second loop over the same variable.","displayName":"1. Set your body template","iconSrc":"assets/img/designer/actions/setVariable.svg"},{"id":"n3foreach","addedByName":"","addedByPicture":"","addedDate":"2026-08-29T16:00:00Z","stepId":"5vchozg4jmtd6qia5","comment":"Point this at the collection you want to iterate. The number of items can change on every run: two items, ten items, or none at all.","displayName":"2. Loop through your collection","iconSrc":"assets/img/designer/actions/foreach.svg"},{"id":"n4script","addedByName":"","addedByPicture":"","addedDate":"2026-08-29T16:00:00Z","stepId":"zsntt0l11mtd6gya5","comment":"Three inputs, nothing else. body = the JSON Body variable. placeholder = the name you used in the template, for example {{users}}. newItem = the JSON of the single item to add, built with tokens from this iteration. Check the Matched By and Error outputs while you are testing.","displayName":"3. Add this item to the body","iconSrc":"assets/img/designer/actions/script-v2.svg"},{"id":"n5savevar","addedByName":"","addedByPicture":"","addedDate":"2026-08-29T16:00:00Z","stepId":"3yv8d289wmtd6l87j","comment":"Writes the script result back into the same variable so the next iteration keeps building on it. This must stay the LAST action inside the loop.","displayName":"4. Save the updated body","iconSrc":"assets/img/designer/actions/setVariable.svg"},{"id":"n6http","addedByName":"","addedByPicture":"","addedDate":"2026-08-29T16:00:00Z","stepId":"yh5o6gm8kmtdfa3x9","comment":"Map the JSON Body variable straight into the request body. It is already a complete JSON string, so no Convert to JSON String action is needed. Set your own URL, method and authorization.","displayName":"5. Send one request with everything","iconSrc":"https://api.au1.zenphi.io/8fbd52ff886945779a295ea344f01b4a/providers/utility/u/e701b0cb-310e-495a-89df-77b3cc7c069e/v/0/ui/assets/icons/utilityhttprequest-v1.svg"}]}