使用JavaScript将多行缩进的json转换为单行 [英] Converting multiline, indented json to single line using javascript

查看:247
本文介绍了使用JavaScript将多行缩进的json转换为单行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想出了以下功能,可以将多行,缩进的json转换为单行

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

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

推荐答案

对于这种问题,我遵循这样的格言:添加正则表达式只会给您带来两个问题.这是一个足够简单的解析问题,因此这是一个解析解决方案:

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

请注意,该代码没有任何错误检查以查看JSON是否格式正确.唯一的错误(字符串没有右引号)将被忽略.

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.

这篇关于使用JavaScript将多行缩进的json转换为单行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆