繁体   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