Javascript Convert JSON to CSV in Browser and Download it as CSV File Using FileSaver.js Library Full Project For Beginners

Javascript Convert JSON to CSV in Browser and Download it as CSV File Using FileSaver.js Library Full Project For Beginners

 

Welcome folks today in this blog post we will be building a simple app which will convert json to csv and will download it as csv file using filesaver.js library in javascript All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to make an index.html file and copy paste the following 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 make a style.css file and copy paste the following 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;
}

 

See also  HTML2PDF.js Example to Add Page Numbers at Top in PDF Document Using Javascript Full Project For Beginners

 

And now make a script.js file and copy paste the following 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 = "";
};

 

See also  Build a Tensorflow Real time Webcam Face Recognition or Detection Web App in Browser Using HTML5 & Javascript Full Project For Beginners

 

And now if you open index.html file inside the browser you will see the below screenshot

 

Leave a Reply