Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove white space from JSON object, but not within quotes

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.

like image 443
dvlden Avatar asked Jul 19 '15 14:07

dvlden


People also ask

Does JSON Stringify remove white spaces?

Calling JSON. stringify(data) returns a JSON string of the given data. This JSON string doesn't include any spaces or line breaks by default.

How do I trim a space in JSON?

First remove the leading and trailing spaces from the key using trim() function. Remove all the spaces, newline or tab present in the key using replace() function and add underscore "_" between the word of the key instead of whitespace.

Is whitespace allowed in JSON?

Full JSON grammar The tab character (U+0009), carriage return (U+000D), line feed (U+000A), and space (U+0020) characters are the only valid whitespace characters.


1 Answers

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"));
like image 156
Avinash Raj Avatar answered Nov 14 '22 23:11

Avinash Raj