从字符串化的JSON中删除逗号,但不从逗号分隔数组中删除逗号

问题描述 投票:-4回答:1

我在描述字段中对包含逗号的JSON数据进行了字符串化。如果我在数据中有撇号或逗号,则AJAX帖子会失败。 如何从var test = JSON.stringify(data)中删除以下内容? test将打印出如下:[{“var1”:“0”,“description”:“this,has,commas”},{“var1”:“1”,“description”:“more,commas”}] 我可以删除描述中的逗号,以便JSON字符串看起来像:[{“var1”:“0”,“description”:“this has commas”},{“var1”:“1”,“description”: “更多逗号”}] 所以留下分隔对象的逗号? 还是更好...... [{“var1”:“0”,“description”:“this \,has \,commas”},{“var1”:“1”,“description”:“more \,commas”}]

需要将数据推回到我的服务器并在更改后加载回我的数据库,逗号和撇号需要保持原状。 test.replace(/,/ g,“”)当然.​​.....摆脱了将对象分开的逗号,并搞砸了我。 任何人都知道正则表达式,这可能会建议一种方法来替换“,”但“不”在“},{”之间? (双引号用于强调) 谢谢你的帮助。

jquery json replace stringify
1个回答
1
投票

怎么样做负面前瞻的test.replace - https://regex101.com/r/WtHcuO/2/

var data = JSON.stringify([{"var1":"0","description":"this, has, commas"},{"var1":"1","description":"more, commas"}]);

var stripped = data.replace(/,(?!["{}[\]])/g, "");

console.log(stripped);

或者,如果你想保留逗号,但是要逃避它们,你可以用\\,代替""

var data = JSON.stringify([{"var1":"0","description":"this, has, commas"},{"var1":"1","description":"more, commas"}]);

var stripped = data.replace(/,(?!["{}[\]])/g, "\\,");

console.log(stripped);
© www.soinside.com 2019 - 2024. All rights reserved.