In this blog post, we will explore how to convert CSV file data to JSON using React JS. We will walk through a step-by-step guide, demonstrating how to read a CSV file, process its contents, and convert it into JSON format. This process can be particularly useful when you need to handle CSV data in a structured and easy-to-use manner.
In our code, we will use the FileReader API, a built-in browser feature that allows us to read file contents and perform the conversion.
Converting CSV File Data to JSON in React
Step 1: Initializing State Variables
import React, { useState } from "react";
const App = () => {
const [jsonData, setJsonData] = useState(null);
// Rest of the component logic
};
In the first step, We initialize the jsonData
state variable using the useState hook inside our App.js
component.
Step 2: Converting CSV to JSON
const convertCSVToJson = (csvData) => {
const lines = csvData.split("\n");
const headers = lines[0].split(",");
const result = [];
for (let i = 1; i < lines.length; i++) {
const obj = {};
const currentLine = lines[i].split(",");
for (let j = 0; j < headers.length; j++) {
obj[headers[j].trim()] = currentLine[j].trim();
}
result.push(obj);
}
return result;
};
Next, we define the convertCSVToJson
function, which takes a csvData
parameter representing the CSV data to be converted. This function performs the conversion process:
- Splitting the CSV data into an array of lines.
- Extracting the headers from the first line of the CSV data.
- Converting each CSV row to a JSON object by mapping the values to the corresponding headers.
- Storing the JSON objects in the
result
array.
Returning the result
array containing the JSON objects.
Step 3: Handling CSV File Input Change
const handleCSVInputChange = (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
const csvData = e.target.result;
const jsonData = convertCSVToJson(csvData);
setJsonData(jsonData);
};
reader.readAsText(file);
};
The handleCSVInputChange
function is triggered when a CSV file is selected using the <input type="file">
element. This function reads the selected file using the FileReader
API, converts the CSV data to JSON using the convertCSVToJson
function, and updates the jsonData
state variable with the converted data.
Step 4: Rendering the UI Component
return (
<div>
<input type="file" accept=".csv" onChange={handleCSVInputChange} />
{jsonData ? (
<div className="json-container">
<pre>{JSON.stringify(jsonData, null, 2)}</pre>
</div>
) : (
<p>Please select a CSV file.</p>
)}
</div>
);
The component rendering logic includes an <input>
element of type "file"
that allows selecting CSV files. The onChange
event is assigned the handleCSVInputChange
function to handle file selection changes.
The component also conditionally renders either the JSON container that contains converted JSON data or a message asking the user to select a CSV file based on the jsonData
state variable. If jsonData
is not null, the JSON container is rendered, displaying the converted JSON data. Otherwise, a message is shown, prompting the user to select a CSV file.
Also, check out:
- Display CSV Data in a Table in React
- How to Visualize CSV Data in React
- How to Validate File Type in React JS
- How to Export Data to CSV in React JS
Output:
![convert csv data to json in react](http://timetoprogram.com/wp-content/uploads/2023/07/convert-csv-data-to-json-in-react.png)
App.js Complete Code:
import React, { useState } from "react";
const App = () => {
const [jsonData, setJsonData] = useState(null);
const convertCSVToJson = (csvData) => {
const lines = csvData.split("\n");
const headers = lines[0].split(",");
const result = [];
for (let i = 1; i < lines.length; i++) {
const obj = {};
const currentLine = lines[i].split(",");
for (let j = 0; j < headers.length; j++) {
obj[headers[j].trim()] = currentLine[j].trim();
}
result.push(obj);
}
return result;
};
const handleCSVInputChange = (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
const csvData = e.target.result;
const jsonData = convertCSVToJson(csvData);
setJsonData(jsonData);
};
reader.readAsText(file);
};
return (
<div>
<input type="file" accept=".csv" onChange={handleCSVInputChange} />
{jsonData ? (
<div className="json-container">
<pre>{JSON.stringify(jsonData, null, 2)}</pre>
</div>
) : (
<p>Please select a CSV file.</p>
)}
</div>
);
};
export default App;
Conclusion
That’s it, we have learned how to convert CSV file data to JSON in React. We were able to read and process CSV data, converting it into a structured JSON format. This allows us to easily work with CSV data and leverage the power of JSON in our React JS projects.