我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>标签

演示:http://jsfiddle.net/K83cK/

Var数据= { "数据":{ “x”:“1”, “y”:“1”, “url”:“http://url.com” }, “事件”:“开始”, “秀”:1、 “id”:50 } . getelementbyid (json)。textContent = JSON。Stringify (data, undefined, 2); < pre id = " json " > < / >之前

其他回答

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

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

使用样式空白:pre <pre>标记还修改可能不希望的文本格式。

考虑你的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);   

我的建议是基于:

将每个'\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 >