Remove the white space from the JSON object but not inside the quotes

So, I have input[type="text"]where I want to insert a JSON object as a configuration. The output in the console is perfect, everything is built in without any cropping, but now inputI have a lot of intervals in this . I would like to get rid of this interval and replace the value input.

Example

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

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

This almost does the job, but also removes the spacing between quotes. Therefore, if I had the / val switch, similar to "sentence": "Sure thing, good to go.", which is converted to "sentence":"Surething,goodtogo.", while I want to keep the interval in quotation marks.

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

Expected 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 it did not work at all.
  • , this.value.replace(/\s+/g, '') , . , , , , , .

, , , .

+4
2

.

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

?

  • ("[^"]*") . , "sentence" "Sure thing ..." (, 1).

  • |

  • \s . .

  • $1 , . , , .

+9

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));
Hide result
+1

Source: https://habr.com/ru/post/1598589/


All Articles