Convert data files between CSV and JSON using simple javascript with npm.
In this article, I am going to show with few easy steps how to convert .csv files into .json and .json file into .csv file using a simple javascript with npm.
Conversion of .json file into .csv file
Let's go step by step
Step 01 |
Run the npm code to initialize the npm package.
npm init -y
Step 02 |
Next lets install the package needed to convert .json file into .csv file.
npm install json2csv -s
Step 03 |
Create a javascript file as app.js. For that run the following code in your terminal.
touch app.js
Step 04 |
We are going to save .json file as .csv file. So next we need to add the file-saver package.
npm i file-saver
Step 05 |
Create a JSON file as user.json and include the following code.
Step 06 |
Include the following code in app.js.
The file user.json that we created earlier will save as newuser.csv.
Step 07 |
Here we go. Now let's run the last command to test the result.
node app.js
Output
When you run the above command you can see the CSV data appear in your console and also you can see a file named newuser.csv appears in your file list. Click it.
That's it. So now we had converted a JSON file into a CSV file
Conversion of .csv file into .json file
Let's use the above created newuser.csv file to convert into a JSON file.
Step 01 |
Install the package needed to convert .csv file into .json file. Run the following command in your terminal.
npm install csvtojson -s
Step 02 |
In the app.js comment all the commands and type the following command.
Step 03 |
Here we go again. Now let’s run the last command to test the result.
node app.js
Output
When you run the above command you can see the JSON data appear in your console and also you can see a file named newuser.json appears in your file list. Click it.
That's all. So now you know how to convert a JSON file into a CSV file and a CSV file into a JSON file.