I want to get csv file from input tag and convert data of csv file into json object. Is there any plugin in react js or any custom code ?
Asked
Active
Viewed 6,663 times
1
-
hi try this url https://stackoverflow.com/questions/61723056/reactjs-converting-a-csv-file-in-local-to-json – Zubair Saif Jun 17 '21 at 08:36
2 Answers
5
You can use an external library like Papa Parse to parse the CSV data.
A simple input tag with type as file would work to read the CSV data.
<input
type="file"
accept=".csv,.xlsx,.xls"
onChange={handleFileUpload}
/>
Please declare handleFileUpload function and use the library inside to parse the read data.
Here's an example which will read a CSV file and log the corresponding JSON:
import Papa from "papaparse";
export default function App() {
return (
<div className="App">
<input
type="file"
accept=".csv,.xlsx,.xls"
onChange={(e) => {
const files = e.target.files;
console.log(files);
if (files) {
console.log(files[0]);
Papa.parse(files[0], {
complete: function(results) {
console.log("Finished:", results.data);
}}
)
}
}}
/>
</div>
);
}
junkie
- 163
- 6
0
You can refer this link below.
https://www.npmjs.com/package/react-papaparse
On handleOnFileLoad method, you will receive data fetched from csv file. You will have a JSON response directly from there. The above link does not support xlxs format. You need to have another npm package for it.
Chandra Shekar
- 61
- 4