简体   繁体   中英

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 got error because my string should be like

 { 
time:  { 
          "from":"now-60d",
          "mode":"quick",
          "to":"now" } 
}

so my question, there is any solution to add double quotes around keys and values of my string ?

thanx

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM