regular expression add double quotes around values and keys in javascript

前端 未结 4 1069
醉话见心
醉话见心 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:22

    Good day Idriss

    if you wanted to place quotes around all the valid key names and values The maybe look at this expression. YCF_L's answer is prefect to what you wanted. But here it is none the less.

    {(?=[a-z])|[a-z](?=:)|:(?=[a-z])|[a-z](?=,)|,(?=[a-z])|[a-z](?=})
    str.replace(/{(?=[a-z])|[a-z](?=:)|:(?=[a-z])|[a-z](?=,)|,(?=[a-z])|[a-z](?
    =})/igm, $&");
    
    0 讨论(0)
  • 2020-12-21 04:34

    maybe you can use :

    str.replace(/([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)/g, "\"$1\":\"$2\"");
    

    Here is regex demo


    Note

    In the group [a-zA-Z0-9-] of characters i use alphabetical digits and a -, maybe you need other so you can use another one

    0 讨论(0)
  • 2020-12-21 04:34

    Unquoted JSON is not really a valid JSON. It is just JavaScript. If you trust the source of this string:

    var obj = eval("'({ 
    time:  { 
          from:now-60d,
          mode:quick,
          to:now } 
     })'");
    

    This is NOT recommended for strings from untrusted sources as it could be a security risk.

    Given that you are getting the data from Kibana which may be trusted, it should be ok to eval the string.

    The other option is to use the regex as probably elaborated by other answers. Alternatively, you may want to fix your Kibana export to give a proper/valid JSON string.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题