Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.
In this article, we’ll look at how to create a JSON to CSV cowith Vue 3 and JavaScript.
Create the Project
We can create the Vue project with Vue CLI.
To install it, we run:
npm install -g @vue/cli
with NPM or:
yarn global add @vue/cli
with Yarn.
Then we run:
vue create json-to-csv
and select all the default options to create the project.
Create the JSON to CSV Converter
To create the JSON to CSV converter, we write:
<template>
<form @submit.prevent="convert">
<div>
<label>json</label>
<textarea v-model="json"></textarea>
</div>
<button type="submit">convert</button>
</form>
<div>
<label>csv</label>
<textarea v-model="csv"></textarea>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
json: "",
csv: "",
};
},
methods: {
convert() {
const parsedJson = JSON.parse(this.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");
this.csv = `${heading}${body}`;
},
},
};
</script>
In the template, we have a form that takes the JSON array string.
The textarea in the form has v-model
to bind the inputted value to the json
reactive property.
The form element has the @submit
directive to listen to the submit event which is triggered when we click convert.
prevent
lets us do client-side form submission instead of server-side.
Below that, we have a div to display the CSV result in the textarea.
We bind it to the csv
reactive property with v-model
.
In the script tag, we have the data
method to return the reactive properties.
Then in the convert
method, we parse the json
string with JSON.parse
.
And then we check if the parsed object is an array and that all entries are objects.
Then we create the heading from the keys of the first entry.
We get the keys with Object.keys
.
Then we get all the values with Object.values
and the join them together with commas with join
.
And we join the rows together with join
and a new line character as the argument.
Finally, we assign a string with heading
and body
combined to this.csv
to display the result in the 2nd textarea.
Conclusion
We can create a JSON to CSV converter with Vue 3 and JavaScript.