Converting multiline, indented json to single line using javascript

别等时光非礼了梦想. 提交于 2019-12-04 06:09:48

问题


I've come up with the following function for converting a multiline, nicely indented json to a single line

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

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

Can anyone come up with something better, both in terms of efficiency and fixing bugs that exist in my implementation (e.g. mine breaks when parsing

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

or

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

回答1:


For this kind of problem, I follow the adage that adding regex just gives you two problems. It's a simple enough parsing problem, so here's a parsing solution:

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

Note that the code does not have any error-checking to see if the JSON is properly formed. The only error (no closing quotes for a string) is ignored.




回答2:


This fixes the two bugs in the question, but probably not very efficiently

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 ;
    });
}


来源:https://stackoverflow.com/questions/5791356/converting-multiline-indented-json-to-single-line-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!