Skip to content

Instantly share code, notes, and snippets.

@palesz
Last active November 1, 2021 14:19
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save palesz/4533361 to your computer and use it in GitHub Desktop.
Save palesz/4533361 to your computer and use it in GitHub Desktop.
JSON to CSV converter
<html>
<head>
<style>
textarea {
height: 300px;
width: 100%;
}
</style>
<script type="text/javascript">
/*** START - CHANGE THIS PART ***/
function getHeader() {
//return with the header columns
return document.getElementById("inp_header").value;
}
function convertItem(item) {
//Put your logic here
return eval(document.getElementById("inp_convertItem").value);
}
function extractItems(jsonObject) {
//returns with the items in an array
return eval(document.getElementById("inp_extractItems").value);
}
/*** END - CHANGE THIS PART ***/
/***** YOU SHOULD NOT CHANGE THE THINGS UNDER THIS LINE *****/
function save_setting(name, value) {
window.localStorage.setItem(name, JSON.stringify(value));
}
function read_setting(name) {
var result = window.localStorage.getItem(name);
result && (result = JSON.parse(result));
return result;
}
function save_settings() {
var settings = {
header: document.getElementById("inp_header").value,
extractItems: document.getElementById("inp_extractItems").value,
convertItem: document.getElementById("inp_convertItem").value,
lastJSON: document.getElementById("json").value
}
save_setting("json_to_csv_settings", settings);
}
function read_settings() {
var settings = read_setting("json_to_csv_settings");
document.getElementById("inp_header").value = settings.header;
document.getElementById("inp_extractItems").value = settings.extractItems;
document.getElementById("inp_convertItem").value = settings.convertItem;
document.getElementById("json").value = settings.lastJSON;
}
function convert() {
save_settings();
var json = document.getElementById("json").value;
var jsonObject = eval("(" + json + ")");
console.log(jsonObject);
var output = document.getElementById("output");
output.value = getHeader();
var items = extractItems(jsonObject);
var itemCount = items.length;
for (var i = 0; i < itemCount; i++) {
var item = items[i];
var itemStr = convertItem(item);
output.value += "\n" + itemStr;
}
}
</script>
</head>
<body onLoad="read_settings();">
<p>
JSON
<textarea id="json"></textarea>
</p>
<p>
Header: <input type="text" id="inp_header"/><br/>
Extract items (jsonObject): <input type="text" id="inp_extractItems"/><br/>
Convert item (item): <input type="text" id="inp_convertItem"/><br/>
</p>
<p><input type="button" onclick="convert();" value="Convert"/></p>
<p>
CSV
<textarea id="output"></textarea>
</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment