The Wayback Machine - https://web.archive.org/web/20240527190934/https://www.geeksforgeeks.org/how-to-convert-csv-to-json-in-reactjs/
Open In App

How to Convert CSV to JSON in ReactJS ?

Last Updated : 18 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Dealing with data in various formats is a common task in web development. CSV (Comma Separated Values) and JSON
(JavaScript Object Notation) are two widely used formats for storing and transmitting data. Converting CSV to JSON is often required when working with data in ReactJS applications.

Approach

  • Begin by creating a new React application using the Create React App or any other method you prefer. This will give you the basic structure to work with.
  • You’ll need to import the necessary dependencies. In this case, we’re using React for building the UI, useState hook to manage state, and PapaParse for parsing CSV files.
  • Build the UI components to display the CSV data and the converted JSON data. Use conditional rendering to display the data only when it’s available. Display the CSV data in a table format and the JSON data in a preformatted text.
  • Create a function to handle CSV file uploads. This function will be triggered when a user selects a CSV file. Check if the file is a CSV file and then use PapaParse to parse the CSV data.
  • Write a function to convert the parsed CSV data into JSON format. You can use JSON.stringify() to convert the data.

Steps to Create a React Application

Step 1: Create a new React project with the following command.

npx create-react-app myproject

Step 2: Switch to the Project Directory

cd myproject

Step 3: Once you have your project set up, run the following command to install the papa parse package.

 npm i papaparse

Project structure

PS

The updated dependencies in package.json file will look like:

{
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"papaparse": "^5.4.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router": "^6.17.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
}

Example: In the below example, the Papaparse library is used to parse a CSV file uploaded by the user and convert it into JSON format, with proper file type validation and display of CSV and JSON data in a React.js application.

CSS
/*App.css*/

.container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    background-color: #a8ffb6;
    border-radius: 8px;
}

.header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
}

.content {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
}

.data-container {
    background-color: #fff;
    padding: 15px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.button {
    padding: 10px 20px;
    background-color: #fb0000;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

table {
    width: 100%;
    border-collapse: collapse;
}

th,
td {
    border: 1px solid rgb(255, 0, 0);
    padding: 8px;
}

pre {
    white-space: pre-wrap;
}
JavaScript
//App.js

import React, { useState } from 'react';
import Papa from 'papaparse';
import './App.css';
function App() {
    const [csvData, setCsvData] = useState([]);
    const [jsonData, setJsonData] = useState([]);
    const csvUploadFn = (event) => {
        const file = event.target.files[0];
        const fileType =
            file.name.split('.').pop().toLowerCase();
        if (fileType !== 'csv') {
            alert('Please upload a CSV file.');
            return;
        }
        Papa.parse(file, {
            complete: (result) => {
                setCsvData(result.data);
            },
            header: true,
        });
    };
    const conversionFn = () => {
        const res = JSON.stringify(csvData, null, 2);
        setJsonData(res);
    };
    return (
        <div className="container">
            <div className="header">
                <h1>CSV to JSON Converter</h1>
                <input type="file"
                    onChange={csvUploadFn}
                    accept=".csv" />
                <button className="button"
                    onClick={conversionFn}>
                    Convert to JSON
                </button>
            </div>
            <div className="content">
                {csvData.length > 0 && (
                    <div className="data-container">
                        <h2>CSV Data</h2>
                        <table>
                            <thead>
                                <tr>
                                    {Object.keys(csvData[0]).map(
                                        (header, index) => (
                                            <th key={index}>
                                                {header}
                                            </th>
                                        ))}
                                </tr>
                            </thead>
                            <tbody>
                                {csvData.map((row, rowIndex) => (
                                    <tr key={rowIndex}>
                                        {Object.values(row).map(
                                            (cell, cellIndex) => (
                                                <td key={cellIndex}>
                                                    {cell}
                                                </td>
                                            ))}
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
                {jsonData && (
                    <div className="data-container">
                        <h2>JSON Data</h2>
                        <pre>{jsonData}</pre>
                    </div>
                )}
            </div>
        </div>
    );
}
export default App;

Step to run the application: Open the terminal and type the following command.

npm start

Output: This output will be visible on http://localhost:3000/ on browser window.

1



Previous Article
Next Article

Similar Reads

How to Convert CSV to JSON file and vice-versa in JavaScript ?
CSV files are a common file format used to store data in a table-like manner. They can be particularly useful when a user intends to download structured information in a way that they can easily open and read on their local machine. CSV files are ideal for this because of their portability and universality. In this article, we will explain how to c
3 min read
Convert JSON file into CSV file and displaying the data using Node.js
There are so many ways to store data for better understanding for individual purposes, in few cases, JSON files will be more suitable in few cases, CSV files, and there are also lots of other types as well like XML, etc. In this article, we will convert the JSON file data into CSV file data and also display that through Node.js. JSON stands for Jav
3 min read
How to Convert JSON file into CSV in PHP ?
In this article, we are going to see how to convert JSON data into a CSV file using PHP. JSON (JavaScript Object Notation) is a dictionary-like notation that can be used to structuring data. It is stored with the extension .json, for example - geeksforgeeks.json On the other hand, CSV (or Comma Separated Value) files represent data in a tabular for
2 min read
How to Convert CSV to JSON in JavaScript ?
In this article, we will explain different ways to change Comma-Separated Values (CSV) data into JavaScript Object Notation (JSON) format, step-by-step. We'll break down each method with clear explanations and examples. There are several approaches available in JavaScript to convert CSV to JSON in JavaScript which are as follows: Table of Content S
3 min read
How to Convert JSON Object to CSV in JavaScript ?
JSON (JavaScript Object Notation) and CSV (Comma-Separated Values) are two widely used formats, each with its own strengths and applications. Fortunately, JavaScript provides powerful tools to facilitate the conversion process between these formats. These are the following approaches: Table of Content Using String ManipulationUsing csvjson library
3 min read
How to Convert CSV to JSON file having Comma Separated values in Node.js ?
A CSV is a comma-separated value file, identified by the .csv extension, is a format used for tabular data storage where values are separated by commas. This article presents a method to convert CSV data to JavaScript Object Notation (JSON) without any relaying on third-party npm packages. Unlike typical conversions, this approach handles scenarios
4 min read
How to convert JSON string to array of JSON objects using JavaScript ?
Given a JSON string and the task is to convert the JSON string to an array of JSON objects. This array contains the values of JavaScript objects obtained from the JSON string with the help of JavaScript. There are two approaches to solve this problem which are discussed below: Approach 1: First convert the JSON string to the JavaScript object using
2 min read
Difference Between JSON and CSV
JSON: JSON refers to JavaScript Object Notation. It is a language-independent, human-readable language used for its simplicity and is most commonly used in web-based applications. The JSON extensions end with a .json. JSON is a user-friendly substitute for XML as it is lightweight and easy to read. It supports data structures like array and objects
2 min read
Export JSON to CSV file in Angular
In this article, we will see how to convert a JSON array into CSV and How to Export CSV as a downloadable file by using Blob in angular 8. The below approach will be followed. Steps to Export the JSON to CSV FileStep 1: Converting JSON to CSV For converting JSON data into CSV format using the following method. The first parameter is the Array of Ob
4 min read
Use of data files (CSV, JSON) in Postman for data-driven testing
It is a software testing method having all test input data stored or documented in a single CSV/JSON file and using a single test script for testing the API request with various input scenarios. It separates the test script logic from the test data. In Postman, we can perform this using variables and data files (CSV or JSON). Key Features of Data-D
2 min read
Article Tags :