Home » How to Convert CSV File Data to JSON in React

How to Convert CSV File Data to JSON in React

how to convert csv file data to json in react js

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:

  1. Splitting the CSV data into an array of lines.
  2. Extracting the headers from the first line of the CSV data.
  3. Converting each CSV row to a JSON object by mapping the values to the corresponding headers.
  4. 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:

Output:

convert csv data to json in react

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.

Leave a Reply

Your email address will not be published.