JSON漂亮的javascript打印

时间:2014-06-19 16:14:08

标签: javascript json

尝试让我的缩进在prettyprint JS函数上正常工作.. 只需要一个简单的JSON stringify,即漂亮的打印。

我处于一个锁定的旧JS服务器环境中。没有JSON obj。我不能使用JSON.stringify或JSON polyfill,所以我必须编写自己的函数..

function prettyprint(obj, ind){
  ind = ind || 0;
  var indent = spaces(ind), str = '';

  if((typeof obj).match(/string|number/) || obj == null){
    return indent + obj;

  } else if(obj.push){

    for(var i=0;i<obj.length;i++){
      str = str + prettyprint(obj[i], ind+2 || 2);
    }
    return indent + '[' + str + ']\n';

  } else {

    str = indent + ' {';
    for(var i in obj){
      str = str + '\n' + indent+'  '+ i + ': ' + prettyprint(obj[i], ind+2);
    }
    return str +'\n';

  }

  return str;


  function spaces(n){
    return Array(n).join(' ');
  }
}

这就是我正在尝试的其他内容.. prettyprint({&#39; a&#39;&#39; b&#39;,&#39; b&#39;:{&#39; C&#39;:&#39; d&#39;}})

2 个答案:

答案 0 :(得分:0)

我认为解决这个问题很有意思;我尝试修改你的代码作为起点,但很快发现在正确的位置管理逗号,并且回车变得非常复杂。

因此我将其转换为遍历传递给它的对象的代码,并在进行格式化输出字符串时发出令牌。我已粘贴下面的代码。

prettyPrint.js:

prettyPrint = function (data) {
    return new prettyPrint.processor(data).output;
}

prettyPrint.indentString = '    ';

prettyPrint.processor = function (data) {
    var indent = 0,
        output = '',
        tokens = {
            value: 1,
            openArray: 2,
            arrayValueSeparator: 3,
            closeArray: 4,
            openObject: 5,
            objectValueName: 6,
            objectValueSeparator: 7,
            closeObject: 8
        };

    function isArray(unknown) {
        return Object.prototype.toString.call(unknown) === '[object Array]';
    }

    function isObject(unknown) {
        return Object.prototype.toString.call(unknown) === '[object Object]';
    }

    function space() {
        var count = indent;
        var result = '';
        while (count--) result += prettyPrint.indentString;
        return result;
    }

    function emit(tokenType, value) {
        switch (tokenType) {
            case tokens.value:
                output += value;
                break;

            case tokens.openArray:
                output += '[';
                break;

            case tokens.arrayValueSeparator:
                output += ', ';
                break;

            case tokens.closeArray:
                output += ']';
                break;

            case tokens.openObject:
                output += '{';
                indent += 1;
                break;

            case tokens.objectValueName:
                output += '\n' + space() + (/^[a-z][a-z0-9_]*$/i.test(value) ? value : "'" + value + "'") + ': ';
                break;

            case tokens.objectValueSeparator:
                output += ',';
                break;

            case tokens.closeObject:
                indent -= 1;
                output += '\n' + space() + '}';
                break;
        }
    }

    function process(data) {
        var p, first;

        if (data === undefined) {
            return;
        }

        // Don't surround null with quotes.
        if (data === null) {
            emit(prettyPrint.tokens.value, 'null');
        }

        else if (isArray(data)) {
            emit(tokens.openArray);
            first = true;
            for (p in data) {
                if (!first) {
                    emit(tokens.arrayValueSeparator);
                }
                process(data[p]);
                first = false;
            }
            emit(tokens.closeArray);
        }

        else if (isObject(data)) {
            emit(tokens.openObject);
            first = true;
            for (p in data) {
                if (data.hasOwnProperty(p) && data[p] !== undefined) {
                    if (!first) {
                        emit(tokens.objectValueSeparator);
                    }
                    emit(tokens.objectValueName, p);
                    process(data[p]);
                    first = false;
                }
            }

            emit(tokens.closeObject);
        }

        else if (data instanceof Date) {
            emit(tokens.value, "'" + data.toISOString() + "'");
        }

        else if (typeof data === 'number') {
            emit(tokens.value, isNaN(data) ? 'null' : data.toString());
        }

        else {
            emit(tokens.value, "'" + data.toString() + "'");
        }
    }

    // Start processing the data.
    process(data);

    // Export the data.
    this.output = output;
}

prettyPrint.html:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Pretty Print Testing</title>
    <script type="text/javascript" src="prettyPrint.js"></script>
</head>
<body>

<pre id="pretty1"></pre>

<pre id="pretty2"></pre>

<script type="text/javascript">
    document.getElementById('pretty1').innerHTML = prettyPrint({ 'a': 'b', 'b': { 'c': 'd' } });

    document.getElementById('pretty2').innerHTML = prettyPrint([1, 2, "three", { 'complex-name': [1] }, { simpleName: { subArray: [1, 2, 3], subString: "Hello" } }]);
</script>

</body>
</html>

输出:

{
    a: 'b',
    b: {
        c: 'd'
    }
}

[1, 2, 'three', {
    'complex-name': [1]
}, {
    simpleName: {
        subArray: [1, 2, 3],
        subString: 'Hello'
    }
}]

我希望这对你有用。

答案 1 :(得分:-1)

这就是我最终的结果:

function pp(obj, ind){
  ind = ind || 0;
  if(typeof obj === 'object' && obj !== null){
    var s = sp(ind) + (obj.push ? '[':'{') + '\n';
    for(i in obj)
      s += sp(ind+2) + i + ': ' + pp(obj[i], ind+2);
    obj = s + sp(ind) + (obj.push ? ']':'}');
  }
  return obj + '\n';

  function sp(n){
    return Array(n).join(' ');
  }
}