Tips > Building Workflows

Flatten Deeply Nested API Responses

Many APIs return deeply nested JSON structures that are painful to work with in expression fields.

Flatten a deeply nested API response with a single Code node instead of chaining Set nodes. Loop over the input items, read the nested values with optional chaining and nullish coalescing, and push a clean flat object for each record. This is common with Stripe, Shopify, and Salesforce webhooks, where values are buried several levels deep and expression-only extraction fails silently on missing keys.

Why flatten nested API responses in a Code node?

Many APIs return deeply nested JSON structures that are painful to work with in expression fields. Instead of chaining multiple Set nodes to extract nested values, use a single Code node to flatten the response into a clean, flat object. This is especially common with webhook payloads from Stripe, Shopify, and Salesforce.

Real-world example: A Stripe invoice.payment_succeeded webhook delivers line items buried three levels deep. Extracting them with expressions alone requires error-prone bracket notation and fails silently when keys are missing.

How do you flatten a nested response with a Code node?

// Mode: Run Once for All Items
const results = [];

for (const item of $input.all()) {
  const invoice = item.json;
  const lineItems = invoice?.data?.object?.lines?.data ?? [];

  for (const line of lineItems) {
    results.push({
      json: {
        invoiceId: invoice.data.object.id,
        customerId: invoice.data.object.customer,
        customerEmail: invoice.data.object.customer_email,
        lineDescription: line.description,
        amount: line.amount / 100,
        currency: line.currency.toUpperCase(),
        periodStart: new Date(line.period.start * 1000).toISOString(),
        periodEnd: new Date(line.period.end * 1000).toISOString(),
        priceId: line.price?.id ?? 'unknown',
        quantity: line.quantity ?? 1,
      }
    });
  }
}

return results;

This replaces what would otherwise be 5-6 Set and IF nodes, and handles missing keys safely with optional chaining and nullish coalescing.

Related: Use Edit Fields in "Map Each" Mode for Simple Renames · Configure Payload Size and Binary Data Mode for Large Files

Showcase builds

19 complete workflows from my own projects, each with its n8n workflow JSON to import. Showcase entries link the file at the end of the article.

See the showcase builds

Keep reading

190 entries grouped by topic, from first workflow to queue mode. Free, no signup.

Browse the encyclopedia

Need it built?

I design, build and run n8n systems for clients. Every engagement starts with a $1,500 diagnostic audit, credited toward the build.

Book an introductory call