loading

How to convert JSON to CSV in react js

We are going to use the npm package to convert json to csv in react. There are several npm packages for JSON to CSV conversion. Here is the list of npm packages

Lets now see, how to convert json to csv with json-2-csv npm

npm i json-2-csv

Methods available to convert json to csv in json-2-csv

There are two methods available in json-2-csv to convert json to csv synchronous and asynchronous method. It needs three paramater array of JSON, a callback function and option for config

json2csv(array, (err, csv) => { ... }, options)

json2csvAsync

for the asynchronous method, We can use json2csvAsync with async await.


import { json2csvAsync } from "json-2-csv";
const Page = () => {
      const toCSV = async (myjson) => {
        const options = {
          delimiter: {
            wrap: '"', // Double Quote (") character
            field: ",",
            eol: "\n"
          },
          //   prependHeader: true,
          sortHeader: false,
        };
        try {
          const csv = await json2csvAsync(JSON.parse(myjson), {
            ...options,
            keys: null,
          });
        } catch (err) {
    
        }
      };
  return (
    <div>Page</div>
  )
}

export default Page

json2csv

for the asynchronous method, we will have to pass a callback function

import { json2csv} from "json-2-csv";
const Page = () => {
let documents = [
    {
        Make: 'Nissan',
        Model: 'Murano',
        Year: '2013',
        Specifications: {
            Mileage: '7106',
            Trim: 'S AWD'
        }
    },
    {
        Make: 'BMW',
        Model: 'X5',
        Year: '2014',
        Specifications: {
            Mileage: '3287',
            Trim: 'M'
        }
    }
];
let json2csvCallback = function (err, csv) {
    if (err) throw err;
    console.log(csv);
};

json2csv(documents, json2csvCallback);

  return (
    <div>Page</div>
  )
}

export default Page

There are npm packages we can use to convert json to csv in javascript, react or next js

About Author

x

Order for website design

Help :