Converting multiline, indented json to single line using javascript

前端 未结 2 1643
遇见更好的自我
遇见更好的自我 2021-01-28 03:18

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

function(text) {
    var outerRX = /((?:\".*?\")|(\\s         


        
相关标签:
2条回答
  • 2021-01-28 03:51

    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.

    0 讨论(0)
  • 2021-01-28 03:52

    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 ;
        });
    }
    
    0 讨论(0)
提交回复
热议问题