i need a valid JSON format to request ES. i have a string like
{
time: {
from:now-60d,
mode:quick,
to:now }
}
This function will add quotes and remove any extra commas at the end of objects
function normalizeJson(str){return str.replace(/"?([\w_\- ]+)"?\s*?:\s*?"?(.*?)"?\s*?([,}\]])/gsi, (str, index, item, end) => '"'+index.replace(/"/gsi, '').trim()+'":"'+item.replace(/"/gsi, '').trim()+'"'+end).replace(/,\s*?([}\]])/gsi, '$1');}
Edit:
This other function supports json arrays.
It also converts single quotes to double quotes, and it keeps quotes off of numbers and booleans.
function normalizeJson(str){
return str.replace(/[\s\n\r\t]/gs, '').replace(/,([}\]])/gs, '$1')
.replace(/([,{\[]|)(?:("|'|)([\w_\- ]+)\2:|)("|'|)(.*?)\4([,}\]])/gs, (str, start, q1, index, q2, item, end) => {
item = item.replace(/"/gsi, '').trim();
if(index){index = '"'+index.replace(/"/gsi, '').trim()+'"';}
if(!item.match(/^[0-9]+(\.[0-9]+|)$/) && !['true','false'].includes(item)){item = '"'+item+'"';}
if(index){return start+index+':'+item+end;}
return start+item+end;
});
}
I also tested the regex with the safe-regex npm module