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

Display json in a readable format in a new tab

本文关键字:格式 json 显示 新选项 选项      更新时间:2023-09-26

我正在尝试在新窗口中以可读格式显示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();
    });
});

把它放到一个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();
尝试类似

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);