简体   繁体   English

javascript中的JSON漂亮打印

[英]JSON pretty print in javascript

Trying to get my indents working right on a prettyprint JS function.. Just need a simple JSON stringify that pretty prints. 试图让我的缩进在prettyprint JS函数上正常工作。只需要一个简单的JSON字符串化该漂亮的打印件即可。

I'm in a locked down older JS server environment. 我处于锁定的较旧JS服务器环境中。 There's no JSON obj. 没有JSON obj。 I can't use JSON.stringify or the JSON polyfills, so I have to write my own func.. 我不能使用JSON.stringify或JSON polyfills,所以我必须编写自己的func ..

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(' ');
  }
}

This is what I'm trying etc.. prettyprint({'a':'b','b':{'c':'d'}}) 这就是我正在尝试的方法。.prettyprint({'a':'b','b':{'c':'d'}})

I thought this would be interesting to solve; 我认为这将很有趣。 and I tried modifying your code as a starting point, but quickly found that managing commas in the right places, and carriage returns was getting very complicated. 我尝试以修改您的代码为起点,但是很快发现在正确的位置管理逗号和回车变得非常复杂。

So I turned it into code that runs through the object passed to it, and emits tokens as it progresses to format an output string. 因此,我将其转换为代码,该代码运行传递给它的对象,并在其格式化输出字符串时发出令牌。 I've pasted the code below. 我粘贴了下面的代码。

prettyPrint.js: 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: 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>

Output: 输出:

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

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

I hope this is useful to you. 我希望这对您有用。

This what I ended up with: 我最终得到的是:

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(' ');
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM