public
Last active

JSON to CSV converter

  • Download Gist
json_to_csv.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
<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>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.