Skip to content Skip to sidebar Skip to footer

Converting Multiline, Indented Json To Single Line Using Javascript

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, in

Solution 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.

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

Post a Comment for "Converting Multiline, Indented Json To Single Line Using Javascript"