从JSON对象中删除空白,但不能在引号内删除

Remove white space from JSON object, but not within quotes

本文关键字:删除 但不能 空白 JSON 对象      更新时间:2023-09-26

所以我有一个input[type="text"],我想粘贴JSON对象作为配置。控制台的输出是完美的,所有内联没有任何修剪,但现在在input我有很多间距。我想去掉空格并替换input值。

$('#widget-json').on('input propertychange', function () {
    var string = this.value.replace(/'s+/g, ''),
        data = $.parseJSON( string );
    $(this).val( string );
});

这几乎完成了工作,但它也删除了引号内的空格。因此,如果我有一个键/值,如"sentence": "Sure thing, good to go.",这将被转换为"sentence":"Surething,goodtogo.",而我想保留引号内的空格。

JSON对象示例

{
    "widget-effect": 3,
    "widget-opacity-color": "#C7C9CF",
    "widget-opacity-slider": "50%",
    "widget-opt-close": false,
    "widget-opt-scroll": true,
    "widget-opt-totop": true,
    "widget-text": "Spacing required within quotes"
}

期望输出示例

{"widget-effect":3,"widget-opacity-color":"#C7C9CF","widget-opacity-slider":"50%","widget-opt-close":false,"widget-opt-scroll":true,"widget-opt-totop":true,"widget-text": "Spacing required within quotes"}
  • 我试过了,jQuery.trim( this.value ),根本不起作用。
  • 我试过了,this.value.replace(/'s+/g, ''),删除了整个空白,甚至在引号内。我知道这可能是正确的结果,但我不知道如何仅在引号外删除它。

我假设regex可以适合跳过替换引号内的空格,但我真的不熟悉它。

使用正则表达式替换操作符

var s = '"sentence": "Sure thing, good to go."';
alert(s.replace(/("[^"]*")|'s/g, "$1"))

上面的正则表达式实际上是做什么的?

  • ("[^"]*")捕获所有双引号块。因此,在上面,"sentence""Sure thing ..."被捕获(意味着这个特定的部分将被存储到索引1的临时缓冲区中)。

  • | OR

  • 's匹配剩余字符串中的所有空格字符。

  • 替换部分中的
  • $1是指第一个捕获组捕获的所有字符。因此,第一个捕获组中的字符被保留,匹配的空格被删除。

更新:

不幸的是,当您转义字符串值中的引号时,regex将中断并停止为剩余的键/值对删除空格

var stri = `"sentence ''"with escaped quotes''" should not break": "Sure thing, good to go."`;
alert(stri.replace(/("(?:''"|[^"])*")|'s/g, "$1"));

尝试使用JSON.stringify

$("#widget-json").on("input propertychange", function () {
    // var string = this.value.replace(/'s+/g, ''),
    var data = JSON.stringify($.parseJSON( this.value ));
    $(this).val( data );
});

var data = {
    "widget-effect": 3,
    "widget-opacity-color": "#C7C9CF",
    "widget-opacity-slider": "50%",
    "widget-opt-close": false,
    "widget-opt-scroll": true,
    "widget-opt-totop": true,
    "widget-text": "Spacing required within quotes"
};
document.write(JSON.stringify(data));