function IsJsonString(str) { if (typeof str !== 'string') return false; try { const result = JSON.parse(str); const type = Object.prototype.toString.call(result); return type === '[object Object]' || type === '[object Array]'; } catch (err) { alert("Json not valide: " + err); return false; } } function submitJson(filename, jsonstring = ""){ if(jsonstring == ""){ jsonstring = $('#jsonfiletxtarea').val(); } if(IsJsonString(jsonstring)){ $.ajax({ type: "PUT", data: jsonstring, headers: {"content-id": "list"}, contentType: "application/json", url: "../server/json/" + filename, success: function(res) { alert("Saved!") } }); } } function showjsonfiles(){ $.getJSON( "../server/json", function( data ) { $.each( data, function(i, item){ var clone = document.importNode(document.querySelector('#JsonFile').content,true); $('[data-class=jsonlink]',clone).text(item); $('[data-class=jsonlink]',clone).attr('href','javascript:openjson("' + item + '");'); $('#JsonFiles').append(clone); }); }); } function openjson(filename){ $.getJSON( "../server/json/" + filename, function( data ) { $('#jsonfiletxtarea').val(JSON.stringify(data, null, 2)); $('#jsonfileform').attr('onsubmit','submitJson("' + filename + '");'); }); } $(document).ready(function() { $(document).on('submit', '#jsonfileform', function() { //prevent page reload on form submit return false; }); $('#jsonfiletxtarea').val(""); showjsonfiles(); });