Skip to content Skip to sidebar Skip to footer

Regular Expression Add Double Quotes Around Values And Keys In Javascript

i need a valid JSON format to request ES. i have a string like { time: { from:now-60d, mode:quick, to:now } } but when i try to use JSON.parse i

Solution 1:

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 alphabeticaldigits and a -, maybe you need other so you can use another one

Solution 2:

This function will add quotes and remove any extra commas at the end of objects

functionnormalizeJson(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.

functionnormalizeJson(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

Solution 3:

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.

Solution 4:

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, $&");

Post a Comment for "Regular Expression Add Double Quotes Around Values And Keys In Javascript"