React is an easy to use JavaScript framework that lets us create front end apps.
In this article, we’ll look at how to create a JSON to CSV with React and JavaScript.
Create the Project
We can create the React project with Create React App.
To install it, we run:
npx create-react-app json-to-csv
with NPM to create our React project.
Create the JSON to CSV Converter App
To create the JSON to CSV converter app, we write:
import React, { useState } from "react";
export default function App() {
const [json, setJson] = useState("");
const [csv, setCsv] = useState("");
const convert = async (e) => {
e.preventDefault();
const parsedJson = JSON.parse(json);
if (
!Array.isArray(parsedJson) ||
!parsedJson.every((p) => typeof p === "object" && p !== null)
) {
return;
}
const heading = Object.keys(parsedJson[0]).join(",");
const body = parsedJson.map((j) => Object.values(j).join(",")).join("n");
setCsv(`${heading}${body}`);
};
return (
<div>
<form onSubmit={convert}>
<div>
<label>json</label>
<textarea
value={json}
onChange={(e) => setJson(e.target.value)}
></textarea>
</div>
<button type="submit">convert</button>
</form>
<div>
<label>csv</label>
<textarea value={csv}></textarea>
</div>
</div>
);
}
We define the json
and csv
states to hold the JSON and CSV strings respectively.
Then we define the convert
function to convert the json
to csv
.
In the function, we call e.preventDefault()
to do client-side form submission.
Then we parse the json
string.
If the JSON isn’t a JSON array or if there are any items that aren’t objects, then we stop running the function.
Otherwise, we proceed to converting the JSON to CSV.
We use the property names as headings.
And we get them with the Object.keys
method.
Then we call parsedJson.map
to map the values to strings by joining the values with commas and then join them together with a new line character.
Then we call setCsv
with the heading
and body
combined.
Below that, we have a form with the onSubmit
prop set to convert
.
convert
is run when we click the convert button since its type is set to submit
.
The text area in the form is bound to the json
state with the value
and onChange
props.
The onChange
prop is set to a function that calls setJson
with e.target.value
.
Below the form, we show a text area that holds the csv
.
We display that by setting the value
prop to it.
Conclusion
We can create a JSON to CSV converter with React and JavaScript.