Tips > Building Workflows

Flatten Deeply Nested API Responses

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

TipIntermediate1 min read

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.

// 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;
```text
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](../data-transformation/01-use-edit-fields-in-map-each-mode-for-simple-renames.md) | [Configure Payload Size and Binary Data Mode for Large Files](../performance-and-large-files/01-configure-payload-size-and-binary-data-mode-for-large-files.md)

Want this running in your stack?

I build production n8n and Cloudflare automation for teams — the same engineering behind HarperFlow. Fixed-price, escrow-protected, US-based.