How can I pretty-print JSON using JavaScript

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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.

Answers

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

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*:)?|�(true|false|null)�|-?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> ;
    });
}

http://jsfiddle.net/KJQ9K/554/ http://jsfiddle.net/KJQ9K/554/

  or full snipped provided here :   
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*:)?|�(true|false|null)�|-?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; }

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils