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 at
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
javascript
function visitObj($container, obj) {
var $ul = $('');
for (var prop in obj) {
var $li = $('- ');
$li.append('' + prop + ': ');
if (typeof obj[prop] === "object") {
visitObj($li, obj[prop]);
} else {
$li.append(''+obj[prop]+'');
}
$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.