This script is designed to enhance the formatting of JSON by adding quotes and eliminating any unnecessary commas at the end of objects.
function adjustJsonFormat(input){return input.replace(/"?([\w_\- ]+)"?\s*?:\s*?"?(.*?)"?\s*?([,}\]])/gsi, (input, key, value, ending) => '"'+key.replace(/"/gsi, '').trim()+'":"'+value.replace(/"/gsi, '').trim()+'"'+ending).replace(/,\s*?([}\]])/gsi, '$1');}
Note:
A different method has been created that also handles JSON arrays.
In addition, it changes single quotes to double quotes and ensures that numbers and booleans do not have additional quotation marks.
function adjustJsonFormat(input){
return input.replace(/[\s\n\r\t]/gs, '').replace(/,([}\]])/gs, '$1')
.replace(/([,{\[]|)(?:("|'|)([\w_\- ]+)\2:|)("|'|)(.*?)\4([,}\]])/gs, (input, start, q1, key, q2, value, end) => {
value = value.replace(/"/gsi, '').trim();
if(key){key = '"'+key.replace(/"/gsi, '').trim()+'"';}
if(!value.match(/^[0-9]+(\.[0-9]+|)$/) && !['true','false'].includes(value)){value = '"'+value+'"';}
if(key){return start+key+':'+value+end;}
return start+value+end;
});
}
The regular expressions used in this function have been validated using the safe-regex npm module