Tips > Building Workflows

Flatten Deeply Nested API Responses

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

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)

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

191 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 a 20-minute call