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


当前回答

您可以尝试这个存储库:https://github.com/amelki/json-pretty-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的区域。

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

我的建议是基于:

将每个'\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输出在<pre>标记中。

使用JSX打印组件的状态

render() {
  return (
    <div>
      <h1>Adopt Me!</h1>
      <pre>
        <code>{JSON.stringify(this.state, null, 4)}</code>
      </pre>
    </div>
  );
}

stringify