How can I pretty-print JSON using JavaScript?

2018-12-31 01:46发布

How can I display JSON in an easy-to-read (for human readers) format? I'm looking primarily for indentation and whitespace, with perhaps even colors / font-styles / etc.

24条回答
低头抚发
2楼-- · 2018-12-31 02:28
旧时光的记忆
3楼-- · 2018-12-31 02:32

I recommend using HighlightJS. It uses the same principle as the accepted answer, but works also for many other languages, and has many pre-defined colour schemes. If using RequireJS, you can generate a compatible module with

python3 tools/build.py -tamd json xml <specify other language here>

Generation relies on Python3 and Java. Add -n to generate a non-minified version.

查看更多
墨雨无痕
4楼-- · 2018-12-31 02:33

I use the JSONView Chrome extension (it is as pretty as it gets :):

Edit: added jsonreport.js

I've also released an online stand-alone JSON pretty print viewer, jsonreport.js, that provides a human readable HTML5 report you can use to view any JSON data.

You can read more about the format in New JavaScript HTML5 Report Format.

查看更多
后来的你喜欢了谁
5楼-- · 2018-12-31 02:34

Douglas Crockford's JSON in JavaScript library will pretty print JSON via the stringify method.

You may also find the answers to this older question useful: How can I pretty-print JSON in (unix) shell script?

查看更多
余生请多指教
6楼-- · 2018-12-31 02:35

Pretty-printing is implemented natively in JSON.stringify(). The third argument enables pretty printing and sets the spacing to use:

var str = JSON.stringify(obj, null, 2); // spacing level = 2

If you need syntax highlighting, you might use some regex magic like so:

function syntaxHighlight(json) {
    if (typeof json != 'string') {
         json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

See in action here: jsfiddle

Or a full snippet provided below:

function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

function syntaxHighlight(json) {
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

var obj = {a:1, 'b':'foo', c:[false,'false',null, 'null', {d:{e:1.3e5,f:'1.3e5'}}]};
var str = JSON.stringify(obj, undefined, 4);

output(str);
output(syntaxHighlight(str));
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }

查看更多
孤独总比滥情好
7楼-- · 2018-12-31 02:36

Use Newtonsoft.Json dll. this is work fine in IE and Chrome

put this code in your razor view

    if (Model.YourJsonSting!= null)
        {
            <pre>
            <code style="display:block;white-space:pre-wrap">
                      @JToken.Parse(Model.YourJsonSting).ToString(Formatting.Indented)
                </code>
            </pre>
        }
查看更多
登录 后发表回答