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


当前回答

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

其他回答

确保JSON输出在<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);   

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

这是给拉拉维尔的,代码点火者 目录: <pre class=“jsonPre”> </pre>

控制器:返回来自控制器的JSON值

返回json_encode($data, JSON_PRETTY_PRINT);

在脚本: <脚本> $ (' .jsonPre ') . html(结果);> < /脚本

结果将是

请使用<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 " > < / >之前