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

标签 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();
    });
});

最佳答案

将其放入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();

关于javascript - 在新选项卡中以可读格式显示 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27705640/

相关文章:

javascript - 使用 html 和 php 日期和手机号码

javascript - 在 1.10.2 Jquery 版本中替换 $.uaMatch

javascript - 包装库 | jQuery 与 Backbone

javascript - PHP 在 ajax 调用中显示脚本的响应

c# - ASP.Net Web 方法 : how to deserialize parameter with inheritance class?

javascript - 如何在保持 Javascript 对象/数组有序的同时保持键查找?

javascript - 如何在CSS文件中设置高度时获取div的高度?

javascript - 保存后如何应用onchange显示/隐藏

json - 如何将 jsonAST.Jint 转换为 int

iphone - 如何以正确的方式解析 GET 响应中的数据?