I'm writing a data viewer page to render objects being sent as JSON from the server. The JSON objects vary in content and plexity, 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 plex. The simplest objects are something like this:
{
"id": "5",
"category": "12",
"created": "25-Sep-2012"
}
while the most plex 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.
I'm writing a data viewer page to render objects being sent as JSON from the server. The JSON objects vary in content and plexity, 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 plex. The simplest objects are something like this:
{
"id": "5",
"category": "12",
"created": "25-Sep-2012"
}
while the most plex 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.
Share Improve this question edited Apr 16, 2014 at 11:31 anaximander asked Nov 12, 2012 at 9:42 anaximanderanaximander 7,1403 gold badges46 silver badges63 bronze badges 2- 1 YOu can post a sample of your JSON.. – coolguy Commented Nov 12, 2012 at 9:45
- If you could paste a sample off your json on somewhere like jsfiddle. would help us help you out – Dominic Green Commented Nov 12, 2012 at 9:46
4 Answers
Reset to default 11You 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.
Tooting my own horn, you could probably adapt JSON2HTML to your needs. The source is at https://github./bloopletech/json2html - see scripts/parse.js for the core that parses the JSON and generates the HTML.
Check out the source code for visualizer.json2html. as it pretty much will visualize any json you throw at it.
Here is a screenshot of what the visualizer was able to do with your json sample above .. again the code is all there and ripe for the picking :)
You can use pre-existing libraries which do JSON to HTML rendering and conversion automatically. But if you want to do more personalized things after reading/rendering the JSON, you can very well rely on plain old JavaScript (after all, all the .js libraries are written using plain old JS)
Basically, you need to render the JSON and extract data out of it. Once you have the data you want, you can convert it to whichever format you want. What you need to do is, perform a check on the type of object and if it is a primitive data type, extract the data, and if not, perform a recursive call until you find primitive data type.
The code snippet for this is :
function renderJson(jsonObject){
for(var objType in jsonObject){
if(typeof jsonObject[objType] === 'object'){
renderJson(jsonObject[objType]);
}
else{
alert(' name=' + objType + ' value=' + jsonObject[objType]);
}
}
}
Try here
This is a very basic code snippet. You can modify this snippet to suit your needs.
Refer http://www.json/js.html for more details on how you can play around with JSON objects and arrays using JS.