Print the JSON object contents

September 21st, 2010 by Alex Leave a reply »

You probably already worked with JSON objects, loaded them from different places like Facebook, Twitter etc. Now did you try echoing the object? Probably you received [Object object], which may not be what you need. Here’s a quick workaround on this, let’s study the whole thing.

We’ll use jQuery for some stuff like AJAX for our test. First let’s create a function to view JSON and let’s load such object from Twitter trends API. The Twitter trends url is: http://api.twitter.com/1/trends.json
Let’s load it..

function jsonEcho(json, level, text) {	
	if (level == null) {
		level = 0;
	}
	if (text == null) {
		text = '';
	}
}
 
function jsonLoaded(data, textresponse) {
	// we'll skip all the checks
	jsonEcho(data, 0, '');
}
 
<textarea id='output' style='width: 99%; height: 400px'>
</textarea>

The level variable will add the left padding to the output, to make the echo look friendly. The text parameter will hold the previously generated output and return it in the end.

Now, for traversing the object properties, we’ll use the standard for (var in object) javascript function. Let’s add it to the jsonEcho function:

function jsonEcho(json, level) {	
	if (level == null) {
		level = 0;
	}
	for (prop in json) {
		// add padding
		for (a = 0; a < level; a++) {
			text += ' ';
		}
 
		// add property
		text += '"'+prop+'": ';
 
		// display property value in case its string
		if (typeof json[prop] == "string") {
			text += '"'+json[prop]+'"'+"\n";
		// else run the jsonEcho recursion
		} else {
			text += '{'+"\n";
			text = jsonEcho(json[prop], level+1, text);
			for (a = 0; a < level; a++) {
			  text += ' ';
			}
			text += '}'+"\n";
		}
	}
 
	return text;
}

As you may see, the function is very simply but, yet, useful. Let’s check if with our jQuery ajax loader:

$(document).bind('ready', function(e) {
	$.ajax({
		url:"http://api.twitter.com/1/trends.json",
		success:jsonLoaded,
		dataType:'jsonp',
		cache:false
	});
});
</script>

Test output:

Download the files below:
jQuery, jsonEcho

This page can be found by searching for:

print json objectjavascript print JSON objectprint json object javascriptjquery print json objecthow to print json objecthow to print json object in javascriptjavascript print jsonprinting json objectjquery print jsonprint json object in javascript



2 comments

  1. Brian says:

    You could also copy and paste the URL into Firefox. Much quicker.

  2. Alex says:

    yes, and do that 10000 more times for all received json objects… would be quicker then? i don’t think so