Converting multiline, indented json to single line using javascript

前端 未结 2 1647
遇见更好的自我
遇见更好的自我 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.

提交回复
热议问题