Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render arbitrary JSON in HTML

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.

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.

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?

EDIT: 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":"[email protected]",
      "userId":"25",
      "userRole":"User"
   }
}

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.

like image 240
anaximander Avatar asked Dec 03 '22 01:12

anaximander


1 Answers

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":"[email protected]",
      "userId":"25",
      "userRole":"User"
   }
});

For a working example, see this fiddle.

like image 173
surj Avatar answered Dec 08 '22 00:12

surj