Tips > Data, APIs & Webhooks

Convert Between Data Formats Using Code Nodes

When APIs speak different languages -- one returns JSON, another expects CSV, a third emits XML -- the Code node is your universal translator.

When APIs speak different languages -- one returns JSON, another expects CSV, a third emits XML -- the Code node is your universal translator. The Code node sandbox includes JSON natively and you can parse or build any text format with standard JavaScript string operations.

Real-world example: A REST API returns a JSON array of invoices. You need to convert it to a CSV file and attach it to an outgoing email via the Send Email node.

// Code node — Run Once for All Items
const items = $input.all();

// Build CSV header
const headers = ['invoice_id', 'customer', 'amount', 'currency', 'date'];
let csv = headers.join(',') + '\n';

// Build CSV rows
for (const item of items) {
  const row = [
    item.json.invoice_id,
    `"${item.json.customer_name.replace(/"/g, '""')}"`, // escape quotes
    item.json.total_amount,
    item.json.currency,
    item.json.invoice_date
  ];
  csv += row.join(',') + '\n';
}

// Return as binary data for email attachment
const binaryData = await this.helpers.prepareBinaryData(
  Buffer.from(csv, 'utf-8'),
  'invoices.csv',
  'text/csv'
);

return [
  {
    json: { rowCount: items.length },
    binary: { data: binaryData }
  }
];
```text
In the Send Email node, set the attachment to the `data` binary property. The recipient gets a clean CSV file attached to the email.

> **Tip: XML Parsing**
>
> For XML-to-JSON conversion, use the built-in XML node or the `xml2js` library available in the Code node: `const { parseStringPromise } = require('xml2js');`

This pattern is critical for integrations between modern APIs and legacy systems that only accept flat file formats.

**Related:** [Flatten Deeply Nested API Responses](../code-node-mastery/01-flatten-deeply-nested-api-responses.md) | [Use the HTTP Request Node as a Universal Connector](../integration-patterns/01-use-the-http-request-node-as-a-universal-connector.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