我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在一个漂亮的打印方式?


当前回答

用预标签包装

<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
    }
]

其他回答

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

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

很多人会对这些问题做出非常奇怪的回答,这就造成了不必要的工作量。

做到这一点最简单的方法包括以下内容

使用JSON. Parse (value)解析JSON字符串 - JSON.stringify(input,undefined,2) 将输出设置为步骤2的值。

在实际代码中,一个例子是(将所有步骤组合在一起):

    var input = document.getElementById("input").value;
    document.getElementById("output").value = JSON.stringify(JSON.parse(input),undefined,2);

输出。value将是你想要显示美化的JSON的区域。

考虑你的REST API返回:

{"Intent":{"Command":"search","SubIntent":null}}

然后你可以按照下面的步骤打印出来:

<pre id="ciResponseText">Output will de displayed here.</pre>   

var ciResponseText = document.getElementById('ciResponseText');
var obj = JSON.parse(http.response);
ciResponseText.innerHTML = JSON.stringify(obj, undefined, 2);   

用预标签包装

<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
    }
]