在HTML中渲染任意JSON [英] Render arbitrary JSON in HTML

查看:344
本文介绍了在HTML中渲染任意JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个数据查看器页面,用于呈现从服务器以JSON格式发送的对象。 JSON对象的内容和复杂性各不相同,从具有少量属性的扁平对象到具有多层嵌套和数组字段的较大结构。我想做的是渲染对象的简单表示,可能是ul。从那里我可以添加东西以允许可点击的展开/折叠行为等。

I'm writing a data viewer page to render objects being sent as JSON from the server. The JSON objects vary in content and complexity, from flat objects with a handful of attributes, to larger structures with several layers of nesting and array fields. What I'd like to do is to render a simple representation of the object, probably as a ul. From there I can add stuff to allow clickable expand/collapse behaviour or something.

我知道这将需要一个我可以在顶层调用的递归函数,这将是然后再次调用它发现的每个嵌套级别。我对Javascript不太自信,而且我对它的了解并不是很远。我也遇到了一个事实,我不知道属性名称 - 不同的对象会有不同的属性,名称不同。

I know this will require a recursive function that I can call on the top level, which will then be called again for each level of nesting it discovers. I'm just not very confident with Javascript, and I'm not getting very far with it. I'm also having trouble with the fact that I don't know the attribute names - different objects will have different attributes, with different names.

是否相对简单渲染像这样的对象的方法,还是我必须改变服务器发送的JSON的形式?

Is there a relatively simple way to render an object like this, or will I have to alter the form of the JSON that the server is sending?

编辑:
JSON的样本可能无济于事;他们变化很大。就像我说的,有些很简单,有些很复杂。最简单的对象是这样的:

Samples of the JSON probably won't help much; they vary wildly. Like I said, some are simple, some are massively complex. The simplest objects are something like this:

{
    "id": "5",
    "category": "12",
    "created": "25-Sep-2012"
}

虽然我目前最复杂的一个是这样的:

while the most complex one I have currently is something like this:

{
   "Attempted":"EditUser",
   "Exception":{
      "Message":"Something",
      "TargetSite":"somewhere",
      "Inner Exception":{
         "Message":"Something else",
         "TargetSite":"somewhere.core",
             "Inner Exception":{
            "Message":"Another message",
            "TargetSite":"something.core.subr",
            "Inner Exception":{
               "Message":"Object reference not set to an instance of an object.",
               "TargetSite":"System.Web.Mvc.ActionResult Update(Int32, System.String, System.String)",
               "StackTrace":[
                  "at Application.Controllers.AdminController.Update(Int32 id, String email, String password) in c:\\Docs\\Apps\\Main\\MyBranch\\Source\\Application\\Application\\Controllers\\AdminController.cs:line 123"
               ],
               "Inner Exception":{

               }
            }
         }
      }
   },
   "details":{
      "userEmail":"test@email.com",
      "userId":"25",
      "userRole":"User"
   }
}

如您所见,它是错误日志的JSON表示,包括软件抛出的异常(敏感细节已被遮盖)。 JSON对象是从审计日志的详细信息字段生成的,因此将来可能会记录其他事件,其详细信息格式与我现在预测的任何格式不同,这就是为什么我要处理任意JSON而不依赖于了解格式。

As you can see, it's a JSON representation of an error log, including the Exception thrown by the software (sensitive details have been obscured). The JSON objects are generated from the "detail" field of an audit log, so in future there may be other events logged whose details are in a different format to anything I predict now, which is why I'm looking to handle arbitrary JSON without reliance on knowing the format.

推荐答案

您可以使用类似BFS算法的东西。这是一个快速示例(取决于jQuery):

You can use something like a BFS algorithm. Here's an quick example (depends on jQuery):

css

ul {
    margin-left: 1em;
}

.json-key {
    font-weight: bold;
}


html

<div id="json-viewer"></div>​

javascript

function visitObj($container, obj) {
    var $ul = $('<ul>');

    for (var prop in obj) {

        var $li = $('<li>');
        $li.append('<span class="json-key">' + prop + ': </span>');
        if (typeof obj[prop] === "object") {
             visitObj($li, obj[prop]);
        } else {
            $li.append('<span class="json-value">'+obj[prop]+'</span>');                   
        }
        $ul.append($li);
    }
    $container.append($ul);
}

所以用你的例子来调用它:

So calling this with your example:

visitObj($('#json-viewer'), {
   "Attempted":"EditUser",
   "Exception":{
      "Message":"Something",
      "TargetSite":"somewhere",
      "Inner Exception":{
         "Message":"Something else",
         "TargetSite":"somewhere.core",
             "Inner Exception":{
            "Message":"Another message",
            "TargetSite":"something.core.subr",
            "Inner Exception":{
               "Message":"Object reference not set to an instance of an object.",
               "TargetSite":"System.Web.Mvc.ActionResult Update(Int32, System.String, System.String)",
               "StackTrace":[
                  "at Application.Controllers.AdminController.Update(Int32 id, String email, String password) in c:\\Docs\\Apps\\Main\\MyBranch\\Source\\Application\\Application\\Controllers\\AdminController.cs:line 123"
               ],
               "Inner Exception":{

               }
            }
         }
      }
   },
   "details":{
      "userEmail":"test@email.com",
      "userId":"25",
      "userRole":"User"
   }
});

有关工作示例,请参阅这个小提琴

For a working example, see this fiddle.

这篇关于在HTML中渲染任意JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆