最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove white space from JSON object, but not within quotes - Stack Overflow

programmeradmin1浏览0评论

So I have an input[type="text"], where I want to paste JSON object as configuration. Output in console is perfect, all inline without any trimming, but now in that input I have lots of spacing. I'd like to get rid of that spacing and replace the input value.

Example

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

    $(this).val( string );
});

That almost do the job, but it also removes spacing within quotes. So if I had a key/val like "sentence": "Sure thing, good to go.", that would get converted into "sentence":"Surething,goodtogo.", while I'd want to preserve spacing within quotes.

JSON Object Example

{
    "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"
}

Desired Output Example

{"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"}
  • I tried, jQuery.trim( this.value ) and that did not work at all.
  • I tried, this.value.replace(/\s+/g, '') and that removed entire whitespace, even within quotes. I know that it is probably correct outcome, but I have no ideas how to remove it only outside of quotes.

I am assuming that that regex could be fitted to skip replacing spacing inside of quotes, but I'm not really familiar with it at all.

So I have an input[type="text"], where I want to paste JSON object as configuration. Output in console is perfect, all inline without any trimming, but now in that input I have lots of spacing. I'd like to get rid of that spacing and replace the input value.

Example

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

    $(this).val( string );
});

That almost do the job, but it also removes spacing within quotes. So if I had a key/val like "sentence": "Sure thing, good to go.", that would get converted into "sentence":"Surething,goodtogo.", while I'd want to preserve spacing within quotes.

JSON Object Example

{
    "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"
}

Desired Output Example

{"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"}
  • I tried, jQuery.trim( this.value ) and that did not work at all.
  • I tried, this.value.replace(/\s+/g, '') and that removed entire whitespace, even within quotes. I know that it is probably correct outcome, but I have no ideas how to remove it only outside of quotes.

I am assuming that that regex could be fitted to skip replacing spacing inside of quotes, but I'm not really familiar with it at all.

Share Improve this question asked Jul 19, 2015 at 14:06 dvldendvlden 2,4628 gold badges39 silver badges61 bronze badges 2
  • 5 Parse it and re-serialize it. – Pointy Commented Jul 19, 2015 at 14:06
  • What was the actual desired behavior? – Zargold Commented Jul 19, 2015 at 14:22
Add a comment  | 

2 Answers 2

Reset to default 14

Use regex alternation operator.

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

What actually the above regex do?

  • ("[^"]*") captures all the double quoted blocks. So in the above, "sentence" and "Sure thing ..." are captured (means this particular part would be stored into a temp buffer of index 1).

  • | OR

  • \s matches all the space characters from the remaining string. So it won't touch the previous matched parts.

  • $1 in the replacement part refers all the chars which are captured by the first capturing group. So chars in the first capturing groups are retained and the matched spaces got removed.

Update:

Unfortunately, when you escape a quote in the value of the string the regex breaks and stops removing spaces for the remaining key/value pairs

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

Try utilizing 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));

发布评论

评论列表(0)

  1. 暂无评论