我如何以易于阅读(供人类阅读)的格式显示JSON?我主要寻找缩进和空白,甚至是颜色/字体样式等。


当前回答

为调试目的显示对象的最简单方法:

console.log("data",data) // lets you unfold the object manually

如果要在DOM中显示对象,应该考虑它可能包含将被解释为HTML的字符串。因此,你需要做一些逃避。。。

var s = JSON.stringify(data,null,2) // format
var e = new Option(s).innerHTML // escape
document.body.insertAdjacentHTML('beforeend','<pre>'+e+'</pre>') // display

其他回答

1行代码(无颜色)中的快速易读JSON输出:

document.documentElement.innerHTML='<pre>'+JSON.stringify(obj, null, 2)+'</pre>';

它工作得很好:

console.table()

在此处阅读更多信息:https://developer.mozilla.org/pt-BR/docs/Web/API/Console/table

我想在这里展示我的jsonAnalyze方法,它只打印了JSON结构,但在某些情况下,打印整个JSON会更有用。

假设您有这样一个复杂的JSON:

let theJson = {
'username': 'elen',
'email': 'elen@test.com',
'state': 'married',
'profiles': [
    {'name': 'elenLove', 'job': 'actor' },
    {'name': 'elenDoe', 'job': 'spy'}
],
'hobbies': ['run', 'movies'],
'status': {
    'home': { 
        'ownsHome': true,
        'addresses': [
            {'town': 'Mexico', 'address': '123 mexicoStr'},
            {'town': 'Atlanta', 'address': '4B atlanta 45-48'},
        ]
    },
    'car': {
        'ownsCar': true,
        'cars': [
            {'brand': 'Nissan', 'plate': 'TOKY-114', 'prevOwnersIDs': ['4532354531', '3454655344', '5566753422']},
            {'brand': 'Benz', 'plate': 'ELEN-1225', 'prevOwnersIDs': ['4531124531', '97864655344', '887666753422']}
        ]
    }
},
'active': true,
'employed': false,
};

然后该方法将返回如下结构:

username
email
state
profiles[]
    profiles[].name
    profiles[].job
hobbies[]
status{}
    status{}.home{}
        status{}.home{}.ownsHome
        status{}.home{}.addresses[]
            status{}.home{}.addresses[].town
            status{}.home{}.addresses[].address
    status{}.car{}
        status{}.car{}.ownsCar
        status{}.car{}.cars[]
            status{}.car{}.cars[].brand
            status{}.car{}.cars[].plate
            status{}.car{}.cars[].prevOwnersIDs[]
active
employed

这是jsonAnalysis()代码:

function jsonAnalyze(obj) {
        let arr = [];
        analyzeJson(obj, null, arr);
        return logBeautifiedDotNotation(arr);

    function analyzeJson(obj, parentStr, outArr) {
        let opt;
        if (!outArr) {
            return "no output array given"
        }
        for (let prop in obj) {
            opt = parentStr ? parentStr + '.' + prop : prop;
            if (Array.isArray(obj[prop]) && obj[prop] !== null) {
                    let arr = obj[prop];
                if ((Array.isArray(arr[0]) || typeof arr[0] == "object") && arr[0] != null) {                        
                    outArr.push(opt + '[]');
                    analyzeJson(arr[0], opt + '[]', outArr);
                } else {
                    outArr.push(opt + '[]');
                }
            } else if (typeof obj[prop] == "object" && obj[prop] !== null) {
                    outArr.push(opt + '{}');
                    analyzeJson(obj[prop], opt + '{}', outArr);
            } else {
                if (obj.hasOwnProperty(prop) && typeof obj[prop] != 'function') {
                    outArr.push(opt);
                }
            }
        }
    }

    function logBeautifiedDotNotation(arr) {
        retStr = '';
        arr.map(function (item) {
            let dotsAmount = item.split(".").length - 1;
            let dotsString = Array(dotsAmount + 1).join('    ');
            retStr += dotsString + item + '\n';
            console.log(dotsString + item)
        });
        return retStr;
    }
}

jsonAnalyze(theJson);

出于调试目的,我使用:

console.debug("%o", data);

https://getfirebug.com/wiki/index.php/Console_APIhttps://developer.mozilla.org/en-US/docs/DOM/console

如果您需要在文本区域中使用此选项,则接受的解决方案将不起作用。

<textarea id='textarea'></textarea>

$(“#textarea”).append(格式JSON(JSON.stringify(jsonobject),true));

function formatJSON(json,textarea) {
    var nl;
    if(textarea) {
        nl = "&#13;&#10;";
    } else {
        nl = "<br>";
    }
    var tab = "&#160;&#160;&#160;&#160;";
    var ret = "";
    var numquotes = 0;
    var betweenquotes = false;
    var firstquote = false;
    for (var i = 0; i < json.length; i++) {
        var c = json[i];
        if(c == '"') {
            numquotes ++;
            if((numquotes + 2) % 2 == 1) {
                betweenquotes = true;
            } else {
                betweenquotes = false;
            }
            if((numquotes + 3) % 4 == 0) {
                firstquote = true;
            } else {
                firstquote = false;
            }
        }

        if(c == '[' && !betweenquotes) {
            ret += c;
            ret += nl;
            continue;
        }
        if(c == '{' && !betweenquotes) {
            ret += tab;
            ret += c;
            ret += nl;
            continue;
        }
        if(c == '"' && firstquote) {
            ret += tab + tab;
            ret += c;
            continue;
        } else if (c == '"' && !firstquote) {
            ret += c;
            continue;
        }
        if(c == ',' && !betweenquotes) {
            ret += c;
            ret += nl;
            continue;
        }
        if(c == '}' && !betweenquotes) {
            ret += nl;
            ret += tab;
            ret += c;
            continue;
        }
        if(c == ']' && !betweenquotes) {
            ret += nl;
            ret += c;
            continue;
        }
        ret += c;
    } // i loop
    return ret;
}