regular expression add double quotes around values and keys in javascript

前端 未结 4 1056
醉话见心
醉话见心 2020-12-21 04:05

i need a valid JSON format to request ES. i have a string like

{ 
time:  { 
          from:now-60d,
          mode:quick,
          to:now } 
}
4条回答
  •  生来不讨喜
    2020-12-21 04:39

    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

提交回复
热议问题