我JSON。Stringify一个json对象

result = JSON.stringify(message, my_json, 2)

上面参数中的2应该是漂亮的输出结果。如果我执行alert(result)之类的操作,它就会这样做。但是,我想通过在div中追加它来将其输出给用户。当我这样做时,我只会显示一行。(我不认为这是工作,因为断点和空格没有被解释为html?)

{ "data": { "x": "1", "y": "1", "url": "http://url.com" }, "event": "start", "show": 1, "id": 50 }

是否有一种输出JSON结果的方法。Stringify到一个div在一个漂亮的打印方式?


当前回答

我的建议是基于:

将每个'\n'(换行符)替换为<br> 用&nbsp;

var x ={“数据”:{“x”:“1”,“y”:“1”,“url”:“http://url.com”},“事件”:“开始”,“显示”:1、“id”:50个}; document.querySelector(“# newquote”)。innerHTML = JSON。Stringify (x, null, 6) .replace(/\n(*)/g, function(匹配,p1) { 返回'<br>' + '&nbsp;'.repeat(p1.length); }); < div id = " newquote " > < / div >

其他回答

完全披露我是这个包的作者,但另一种以可读的方式输出JSON或JavaScript对象的方法是nodedump, https://github.com/ragamufin/nodedump

我的建议是基于:

将每个'\n'(换行符)替换为<br> 用&nbsp;

var x ={“数据”:{“x”:“1”,“y”:“1”,“url”:“http://url.com”},“事件”:“开始”,“显示”:1、“id”:50个}; document.querySelector(“# newquote”)。innerHTML = JSON。Stringify (x, null, 6) .replace(/\n(*)/g, function(匹配,p1) { 返回'<br>' + '&nbsp;'.repeat(p1.length); }); < div id = " newquote " > < / div >

如果这确实是为用户准备的,比仅仅输出文本更好,您可以使用像https://github.com/padolsey/prettyprint.js这样的库将其输出为HTML表。

您可以尝试这个存储库:https://github.com/amelki/json-pretty-html

用预标签包装

<pre> { JSON.stringify(todos, null, 4)}</pre>

输出将是

[
    {
        "id": "6cbc8fc4-a89e-4afa-abc1-f72f27b14271",
        "title": "shakil",
        "completed": false
    },
    {
        "id": "5ee68df8-e152-46ae-82e2-8eb49f477d6f",
        "title": "kobir",
        "completed": false
    }
]