[英]Remove white space from JSON object, but not within quotes
所以我有一個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": "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, '')
並刪除了整個空格,即使在引號內。 我知道這可能是正確的結果,但我不知道如何僅在引號之外將其刪除。我假設該正則表達式可以適合跳過替換引號內的間距,但我根本不熟悉它。
使用正則表達式交替運算符。
var s = '"sentence": "Sure thing, good to go."'; alert(s.replace(/("[^"]*")|\\s/g, "$1"))
上面的正則表達式實際上做了什么?
("[^"]*")
捕獲所有雙引號塊。所以在上面, "sentence"
和"Sure thing ..."
被捕獲(意味着這個特定部分將被存儲到索引 1 的臨時緩沖區中) .
|
或者
\\s
匹配剩余字符串中的所有空格字符。 所以它不會觸及之前匹配的部分。
替換部分中的$1
是指第一個捕獲組捕獲的所有字符。 所以第一個捕獲組中的字符被保留,匹配的空格被刪除。
更新:
不幸的是,當您轉義字符串值中的引號時,正則表達式會中斷並停止刪除剩余鍵/值對的空格
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.