Javascript Convert JSON to CSV in Browser & Download it as CSV File by FileSaver.js Library complete Project

Welcome Learner today in this blog post we will be building a simple app that will convert JSON to CSV and will download it as a CSV file using the filesaver.js library in javascript. All the Complete source code of the application is shown Down.

Let’s get started

In order to lets started, you need to make a file index.html and copy-paste the mentioned code

index.html

<div class="page-wrap">
  <h1>JSON to CSV</h1>
  <main class="converter-wrap">
  <section class="side-wrap">
    <p>Paste JSON here</p>
    <textarea id="text-json" placeholder='add json here...'></textarea>
    <div class="button-wrap">
      <button class="button-json" id="submit-json" onclick="sendJSON()">Submit</button>
      <button class="button-json" id="clear-json" onclick="clearJSON()">Clear</button>
    </div>
  </section>
  <section class="side-wrap">
    <p>CSV Output</p>
    <textarea id="text-csv"></textarea>
    <div class="button-wrap">
      <input id="file-name" placeholder="filename"></input>
      <select id="type-select">
        <option value="txt">.txt</option>
        <option value="csv">.csv</option>
      </select>
      <button id="save-csv" onclick="saveCSV()">Save File</button>
    </div>
  </section>
  </main>
<p class="details" id="button-generate">You can generate some sample JSON <a href="https://mockaroo.com/" target='_blank'>here</a>.</p>
</div>

<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/14082/FileSaver.js"></script>

And now create a style.css file and copy-paste the Given code

style.css

body {
  font-family: sans-serif;
  background-color: #eee;
  color: #424242;
}

textarea {
  width: 95%;
  min-height: 200px;
  overflow: scroll;
  background-color: #222634;
  color: #BEBEBE;
  border-radius: 2px;
  border: 1px solid #222634;
  padding: 10px;
}

placeholder {
  color: #BEBEBE;
}

input {
  border-radius: 2px;
  border: 1px solid #fff;
    background-color: #222634;
  padding: 5px;
  width: 100px;
  color: #BEBEBE
}

select {
  height: 25px;
  border-radius: 2px;
}

::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */
  color: #BEBEBE;
  opacity: 0.5; /* Firefox */
}

.page-wrap {
  max-width: 800px;
  padding: 10px 60px;
  display: flex;
  justify-content: center;
  flex-direction: column;
}

.converter-wrap {
  display: flex;
}

.side-wrap {
  display: flex;
  flex-direction: column;
  width: 50%;
  margin: 10px;
}

h1 {
  color: #222634;
/*   text-align: center; */
}

button {
  background-color: #173BAE;
  max-width: 100px;
  padding: 5px 15px;
  border-radius: 2px;
  margin-top: 10px;
  color: white;
  border: none;
}

button:hover {
  cursor: pointer;
}

#clear-json {
  background-color: #ef5350;
}

.details {
/*   text-align: center; */
  padding-top: 20px;
  font-size: 0.8rem;
}

 

READ Create a JSON File Compressor Web App Using FileSaver.js Library in JS Complete Project For learner

And now create a script.js file and copy-paste the Given code.

script.js

const jsonBox = document.getElementById("text-json");
const csvBox = document.getElementById("text-csv");
const fileName = document.getElementById("file-name");
const typeSelect = document.getElementById("type-select");

const sendJSON = () => {
  const boxValue = jsonBox.value;
  if (validJSON(boxValue) && boxValue != "") {
    const input = JSON.parse(boxValue);
    const header = Object.keys(input[0]);
    const dataLines = input.map(x => {
      return Object.values(x)
        .toString()
        .replace(/,/g, ", ");
    });
    csvBox.innerHTML =
      header.toString().replace(/,/g, ", ") + "\r\n" + dataLines.join("\r\n");
  } else {
    csvBox.innerHTML = "Must be valid, flattened JSON!";
  }
};

const validJSON = str => {
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }
  return true;
};

const clearJSON = () => {
  jsonBox.value = "";
};

const saveCSV = () => {
  const fileType =
    typeSelect.value === "txt" ? ["plain", "txt"] : ["csv", "csv"];
  const blob = new Blob([csvBox.value], {
    type: `text/${fileType[0]};charset=utf-8`
  });
  if (fileName.value === "") fileName.value = "json";
  saveAs(blob, `${fileName.value}.${fileType[1]}`);
  fileName.value = "";
};

Leave a Comment

Your email address will not be published. Required fields are marked *