Skip to content

Data Import

Every chart type accepts data via setData(). What you pass in can come from anywhere — a hardcoded array in your script, a JSON file on the server, a CSV export, or a live API endpoint. RareCharts ships with four adapters that cover the common cases, plus a mapping system that handles the boring part of transforming raw source fields into what the chart expects.

Direct data

The simplest case: your data is already in the right shape and lives in your script. Just pass it straight in.

new RareCharts.Line('#chart', { height: 280 })
  .setData([
    { date: '2026-01-01', value: 142 },
    { date: '2026-01-02', value: 159 },
    { date: '2026-01-03', value: 151 },
  ]);

Each chart type has its own data format — see the chart’s documentation page for the exact shape it expects.

Adapters

When data comes from a file or an API, use one of the built-in adapters. They fetch the data, apply a field mapping, and return a clean array ready for setData().

All adapters (except fromArray) are async. Use them with await — in a <script type="module">, where the snippets below run as written, or inside an async function — or chain with .then().

The adapters are available as RareCharts.fromJson, RareCharts.fromCsv, RareCharts.fromApi, and RareCharts.fromArray.

Field mapping

Every adapter accepts a mapping object as its second argument. The mapping tells the adapter how to translate your source fields into the fields the chart expects.

Each key in the mapping is the output field name. The value can be:

  • A function row => value — for transformations, type coercion, or computed fields
  • A string — a direct field name from the source row

Whatever the mapping returns, date is read as a date (a Date, an ISO string or epoch milliseconds) and value as a number — with a function as with a field name, so a CSV's '148.50' becomes 148.5 either way.

A date string without a zone ('2026-01-01') is read as local midnight, as the charts read it by default. The adapters take no time zone: for a chart with timeZone: 'UTC', map such a date to epoch milliseconds — date: row => Date.parse(row.date) reads '2026-01-01' as UTC midnight — or pass the rows' strings to setData without an adapter, and the chart reads them in its own zone (Dates and time zones).

// Source row looks like: { ts: '2026-01-01', close: '148.50', volume: '2300000' }
// Chart expects:         { date: Date, value: number }

const mapping = {
  date:  row => row.ts,               // '2026-01-01': read as local midnight
  value: row => +row.close,           // coerce string to number
};

Rows where date cannot be read as a date or value is not a finite number are filtered out automatically; an empty value is kept (see the mapping reference). This keeps garbage data from making your chart look broken.

fromJson

Fetches a JSON file and applies a mapping.

const chart = new RareCharts.Line('#chart', { height: 280 });
const data = await RareCharts.fromJson('/data/prices.json', {
  date:  row => row.date,
  value: row => +row.close,
});

chart.setData(data);

The adapter handles three common JSON shapes automatically, without any configuration:

  • Array at root — [{ ... }, { ... }]
  • Data property — { data: [{ ... }] }
  • Object of objects — { '2026-01': { ... }, '2026-02': { ... } } (iterates values)

For anything more exotic, use fromApi with a custom transform function.

fromCsv

Fetches a CSV file. All values come in as strings — the mapping is where you coerce types.

const data = await RareCharts.fromCsv('/data/revenue.csv', {
  date:  row => row.month,
  value: row => parseFloat(row.revenue_usd),
});

CSV headers become field names. If your CSV has a header row (it should), the adapter handles it correctly — D3's CSV parser is doing the actual work under the hood.

fromApi

Fetches from a REST endpoint. Supports custom headers for authenticated APIs and a transform function for non-standard response shapes.

Basic usage:

const data = await RareCharts.fromApi('https://api.example.com/metrics', {
  date:  row => row.timestamp,
  value: row => row.count,
});

With authentication:

const data = await RareCharts.fromApi(
  'https://api.example.com/private/metrics',
  { date: row => row.ts, value: row => row.val },
  { headers: { 'Authorization': 'Bearer ' + token } }
);

With a custom transform — when the response has a non-standard shape that the auto-detection can’t handle:

const data = await RareCharts.fromApi(
  'https://api.example.com/report',
  { date: row => row.period, value: row => row.total },
  {
    transform: response => response.results.entries,
  }
);

In that case transform receives the raw parsed JSON and should return a plain array of row objects.

If the HTTP response is not OK (4xx, 5xx), fromApi throws an error with the status code. Handle it if you need a graceful fallback:

try {
  const data = await RareCharts.fromApi(url, mapping);
  chart.setData(data);
} catch (err) {
  console.error('Failed to load chart data:', err.message);
}

fromArray

For data that’s already in memory but needs field remapping. Synchronous — no await needed.

const chart = new RareCharts.Line('#chart', { height: 280 });
const raw = myApp.getMetrics(); // returns [{ ts, val }, ...]

const data = RareCharts.fromArray(raw, {
  date:  row => row.ts,
  value: row => row.val,
});

chart.setData(data);

This is useful when you’re pulling data from a state store, another library, or a function that returns a plain array — and the field names don’t match what the chart expects.

Live updates

setData() can be called any number of times on the same chart instance. Call it again when your data changes — the chart re-renders in place.

const chart = new RareCharts.Line('#chart', { height: 280 });

// Initial load
const data = await RareCharts.fromApi(url, mapping);
chart.setData(data);

// Refresh every 30 seconds
setInterval(async () => {
  const fresh = await RareCharts.fromApi(url, mapping);
  chart.setData(fresh);
}, 30_000);

Mapping reference

Value type Behavior Example
Function Called with each row; the return value is used (date read as a date, value as a number) row => row.ts.slice(0, 10)
String Treated as a field name — row[fieldName]; date is parsed, value coerced to a number 'close_price'

Invalid rows are filtered out automatically:

  • Rows where date is present but cannot be read as a date (a Date, an ISO string or epoch milliseconds)
  • Rows where value is present but is not a finite number (NaN, Infinity, text such as 'n/a'). An empty value ('' — a blank CSV cell — or null) is not filtered: the row is kept as it is, and a line chart skips that point