在新选项卡中以可读格式显示json

时间:2014-12-30 12:37:51

标签: javascript jquery json

我正在尝试以可读的格式在新窗口中显示json。我有一个按钮,当你点击一个新标签时,里面会出现json。但是,在新窗口中,json仍然没有格式化,它显示为纯文本。但是,在console.log中,格式正确。我不明白为什么会有所不同。

$('.showRawJson').click(function () {
    $.getJSON('somelink', function (json) {
        var myjson = JSON.stringify(json, null, 2);
        // In the console the json is well formatted
        console.log(myjson);
        var x = window.open();
        x.document.open();
        // Here in the new tab the json is NOT formatted
        x.document.write(myjson);
        x.document.close();
    });
});

2 个答案:

答案 0 :(得分:4)

将其放入pre标记中,并在显示期间保留空白。你的代码改变了一点:

    var myjson = JSON.stringify(json, null, 2);
    console.log(myjson);
    var x = window.open();
    x.document.open();
    x.document.write('<html><body><pre>' + myjson + '</pre></body></html>');
    x.document.close();

答案 1 :(得分:0)

尝试使用JSON.stringify<pre>标记。

要使用此功能,您需要将字符串转换为对象,然后再将其转换为字符串:

示例:

http://jsfiddle.net/yEez8/

var jsonStr = $("pre").text();
var jsonObj = JSON.parse(jsonStr);
var jsonPretty = JSON.stringify(jsonObj, null, '\t');

$("pre").text(jsonPretty);