[英]Replace all instances of a period between 2 sets of repeating characters
I Have a JSON block of code that I'm being sent by a vendor. 我有一个由供应商发送的JSON代码块。 Before I can use it, I have to manipulate all the keys (approx 65) to remove periods or it interfere's with my applications usage.
在使用它之前,我必须操纵所有键(大约65个)以删除句点,否则会干扰我的应用程序的使用。 Trying to use a regex pattern with a JS replace function to replace them with underscores.
尝试使用带有JS replace函数的正则表达式模式将其替换为下划线。 Presume I have the following string:
假设我有以下字符串:
JSON_String = '{ "Test.String.One" : "Answer.One" , "Test.String.Two" : "Answer.Two" , "Test.String.Three" : "Answer.Three"}';
I need a Regex Pattern that will replace all the periods in the keys but not in the values. 我需要一个正则表达式模式,它将替换键中的所有句点,而不替换值中的所有句点。 So that would be all periods either between { and : or between , and :
因此,将是{和:之间,或之间,以及:
The result when done should look like this: 完成后的结果应如下所示:
JSON_String = '{ "Test_String_One" : "Answer.One" , "Test_String_Two" : "Answer.Two" , "Test_String_Three" : "Answer.Three"}';
The application is using a Rhino implementation of Javascript so some things like the \\K don't appear to work (unless I did something wrong in my testing). 该应用程序使用的是Rhino的Javascript实现,因此\\ K之类的东西似乎不起作用(除非我在测试中做错了什么)。
Anybody who can provide the right search pattern to accomplish this? 谁能提供正确的搜索模式来完成此任务?
I'm not against using a loop if it can't be done in one call. 我不反对使用循环,如果它不能在一个调用中完成。
something like the below would be fine. 像下面这样的东西会很好。 I just need to get something working.
我只需要使一些工作。
while (JSON_String.search(/regex/g) != -1)
{
JSON_String = JSON_String.replace(/regex/g,'_')
}
You could do it with regex but it may be more complicated than what you need to do. 您可以使用正则表达式来做,但是它可能比您需要做的要复杂。 This can easily be accomplished with
Object.keys()
and .replace()
: 这可以通过
Object.keys()
和.replace()
轻松实现:
var JSON_String = { "Test.String.One" : "Answer.One" , "Test.String.Two" : "Answer.Two" , "Test.String.Three" : "Answer.Three"}; document.querySelectorAll('code')[0].innerHTML = JSON.stringify(JSON_String); function UnderscoreKeys(obj) { var keys = Object.keys(obj), temp = {}; for(var a = 0, len = keys.length; a < len; a++) { temp[keys[a].replace(/\\./g, "_")] = obj[keys[a]]; } return temp; } JSON_String = UnderscoreKeys(JSON_String); document.querySelectorAll('code')[1].innerHTML = JSON.stringify(JSON_String);
<strong>Before:</strong><br /> <pre> <code> </code> </pre> <br /><br /><strong>After:</strong><br /> <pre> <code> </code> </pre>
you can simply use. 您可以简单地使用。
function underscore(){
var a = dotted = JSON.parse(JSON_string), underscored = {};
for(var i in dotted){
underscored[i.repace(/\./, "_")] = dotted[i];
}
return JSON.stringify(underscored)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.