简体   繁体   English

在JSON中使用不转义的花括号替换字符串

[英]String replace with with unescaped curly brace in JSON

I'm trying to replace a value in a string with a double curly (used by postman for variable substitution), but every time I try to quote or escape the braces, I always get additional escaped quotes or double escaped braces, all of which break the substitution: 我试图用双倍大写字母替换字符串中的值(邮递员用于变量替换),但是每次尝试引用或转义大括号时,我总是得到附加的转义引号或双转义大括号,所有这些打破替代:

Original String: 原始字串:

"header": [{"key": "x-device-auth","value": "\"token\""}]

OriginalString.replace('token','{{token}}')

Result: 结果:

"header":[{"key":"x-device-auth","value":"\"{{token}}\""}]

If I search for .replace('\\"token\\"','{{token}}') , I don't get a match. 如果我搜索.replace('\\"token\\"','{{token}}') ,则找不到匹配项。 The final string needs to be: 最后的字符串必须是:

"header": [{"key": "x-device-auth","value": "{{token}}"}]

You should be looking for token with the escaped wrapping double quotes, since you also want to replace those. 您应该使用转义的双引号来查找token ,因为您还希望替换那些双引号。

 var originalString = '"header": [{"key": "x-device-auth","value": "\\\\"token\\\\""}]'; console.log(originalString); console.log(originalString.replace('\\\\"token\\\\"','{{token}}')); originalString = '"header": [{"key": "x-device-auth","value": "\\"token\\""}]'; console.log(originalString); console.log(originalString.replace('"token"','{{token}}')); 

I have added two cases, one with the original string actually containing backslashes (first originalstring definition). 我添加了两种情况,一种情况是原始字符串实际上包含反斜杠(第一个originalstring定义)。 The second without. 第二个没有。 Choose the one, that best matches your actual input :-) 选择与您的实际输入最匹配的一个:-)

I dont see the input string is having proper escape characters applied. 我看不到输入字符串已应用适当的转义字符。 As you posted question in javascript tag, I tried below with javascript and its giving required results. 当您在javascript标记中发布问题时,我在下面尝试使用javascript及其给出所需的结果。

var str = "\"header\": [[{\"key\": \"x-device-auth\",\"value\": \"token\"}]";
  var res = str.replace('token','{{token}}');

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

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