簡體   English   中英

使用javascript將多行縮進的json轉換為單行

[英]Converting multiline, indented json to single line using javascript

我已經提出了以下函數,用於將多行,精確縮進的json轉換為單行

function(text) {
    var outerRX = /((?:".*?")|(\s|\n|\r)+)/g,
        innerRX = /^(\s|\n|\r)+$/;

    return text.replace(outerRX, function($0, $1) {
        return $1.match(innerRX) ? "" : $1 ;
    });
}

任何人都可以提出更好的方法,無論是在效率方面還是修復我的實現中存在的錯誤(例如解析時我的中斷)

{
    "property":"is dangerously
             spaced out" 
}

要么

{
    "property":"is dangerously \" punctuated" 
}

對於這類問題,我遵循這樣的格言:添加正則表達式只會給你帶來兩個問題。 這是一個簡單的解析問題,所以這是一個解析解決方案:

var minifyJson = function (inJson) {
  var outJson, // the output string
      ch,      // the current character
      at,      // where we're at in the input string
      advance = function () {
        at += 1;
        ch = inJson.charAt(at);
      },
      skipWhite = function () {
        do { advance(); } while (ch && (ch <= ' '));
      },
      append = function () {
        outJson += ch;
      },
      copyString = function () {
        while (true) {
          advance();
          append();
          if (!ch || (ch === '"')) {
            return;
          }
          if (ch === '\\') {
            advance();
            append();
          }
        }
      },
      initialize = function () {
        outJson = "";
        at = -1;
      };

  initialize();
  skipWhite();

  while (ch) {
    append();
    if (ch === '"') {
      copyString();
    }
    skipWhite();
  }
  return outJson;
};

請注意,代碼沒有任何錯誤檢查,以查看JSON是否正確形成。 唯一的錯誤(沒有字符串的結束引號)將被忽略。

這解決了問題中的兩個錯誤,但可能效率不高

function(text) {
    var outerRX = /((?:"([^"]|(\\"))*?(?!\\)")|(\s|\n|\r)+)/g,
    innerRX = /^(\s|\n|\r)+$/;

    return text.replace(outerRX, function($0, $1) {
        return $1.match(/^(\s|\n|\r)+$/) ? "" : $1 ;
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM