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 one API returns JSON, another expects CSV, and a third emits XML, use the Code node as a universal translator. Its sandbox includes JSON natively, and standard JavaScript string operations build or parse any text format. You can even output the result as binary data and attach it directly to an email or upload it to storage.

What does the Code node do for format conversion?

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.

How do you convert JSON to CSV in a Code 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 }
  }
];

In the Send Email node, set the attachment to the data binary property. The recipient gets a clean CSV file attached to the email.

How do you convert XML instead?

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 · Use the HTTP Request Node as a Universal Connector

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