pretty-print JSON using JavaScript

后端 未结 24 1675
一向
一向 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条回答
  •  死守一世寂寞
    2020-11-21 07:15

    If you need this to work in a textarea the accepted solution will not work.

    $("#textarea").append(formatJSON(JSON.stringify(jsonobject),true));

    function formatJSON(json,textarea) {
        var nl;
        if(textarea) {
            nl = "
    ";
        } else {
            nl = "
    "; } var tab = "    "; 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; }

提交回复
热议问题