简体   繁体   English

正则表达式在javascript中的值和键周围添加双引号

[英]regular expression add double quotes around values and keys in javascript

i need a valid JSON format to request ES.我需要一个有效的 JSON 格式来请求 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但是当我尝试使用JSON.parse出现错误,因为我的字符串应该像

 { 
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在字符组[a-zA-Z0-9-] ,我使用alphabetical digits和 a - ,也许您需要其他digits ,因此您可以使用另一个字符

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.这个其他函数支持 json 数组。

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我还使用安全正则表达式npm 模块测试了正则表达式

Unquoted JSON is not really a valid JSON.未加引号的 JSON 并不是真正有效的 JSON。 It is just JavaScript.它只是 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.鉴于您从 Kibana 获取可能受信任的数据,评估字符串应该没问题。

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.或者,您可能希望修复 Kibana 导出以提供正确/有效的 JSON 字符串。

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. YCF_L 的回答完全符合您的要求。 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, $&");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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