pretty-print JSON using JavaScript

后端 未结 24 1759
一向
一向 2020-11-21 06:45

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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 07:18

    To highlight and beautify it in HTML using Bootstrap:

    function prettifyJson(json, prettify) {
        if (typeof json !== 'string') {
            if (prettify) {
                json = JSON.stringify(json, undefined, 4);
            } else {
                json = JSON.stringify(json);
            }
        }
        return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
            function(match) {
                let cls = "";
                if (/^"/.test(match)) {
                    if (/:$/.test(match)) {
                        cls = "";
                    } else {
                        cls = "";
                    }
                } else if (/true|false/.test(match)) {
                    cls = "";
                } else if (/null/.test(match)) {
                    cls = "";
                }
                return cls + match + "";
            }
        );
    }
    

提交回复
热议问题