Skip to content

Instantly share code, notes, and snippets.

@andyrichardson
Last active April 22, 2021 11:07
Show Gist options
  • Save andyrichardson/3d496c642929cda8c396361c23f6600f to your computer and use it in GitHub Desktop.
Save andyrichardson/3d496c642929cda8c396361c23f6600f to your computer and use it in GitHub Desktop.
Conversion of JSON to CSV without libraries

JSON to CSV

Conversion of JSON to CSV without libraries

const jsonToCSV = (data, columns) => {
  // Create CSV string
  const makeRow = (columns) => columns.map((c) => (c === undefined ? '' : `${JSON.stringify(c)}`)).join(',') + '\n';
  const resolvePath = (data, path) => path.reduce((obj, p) => obj[p], data);

  return [
    makeRow(columns.map(c => c.title)),
    ...data.map(d => makeRow(columns.map(c => resolvePath(d, c.path)))),
  ].join('');
};

Example

Input

const data = [
  { id: 1, user: { name: 'Charlotte' } },
  { id: 2, user: { name: 'Stefan' } },
]
const columns = [
  { title: 'ID', path: ['id'] },
  { title: 'Name', path: ['user', 'name'] },
];

jsonToCSV(data, columns);

Output

"ID","Name"
1,"Charlotte"
2,"Stefan"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment