21 December 2012

Bookmarklet: add json to your console

If you’re working with APIs and loading JSON directly in your browser, you should make it easy to read via JSONView for firefox or chrome. However, it can be frustrating that you don’t have access to the JSON in the JavaScript console. Here’s a lazy hack to get that—try the AddJSON bookmarklet.

It’d be nice if JSONView did this already, but I couldn’t find it doing this—please let me know if I’m wrong.

The code

I threw it together using my handy-dandy bookmarklet generator with the "include jquery" option and the following simple code:

var url = document.location.href.split('?');
if (url[1]) {
    url[1] = url[1].replace(/callback=[^&]*(&|$)/, '');
}
$.ajax({
    url: url.join('?'),
    dataType: 'json',
    type: 'get',
    success: function(data) {
        window.json = data;
        console.log('window.json', data);
    }
});

An example

Open up the reddit homepage as JSON then hit the bookmarklet. Now you can do whatever you want with the json object:

// see how many titles there are
json.data.children.length;

// print out the title of each post
json.data.children.forEach(function(x,i) { console.log(i, x.data.title); });

// sum the total number of downvotes on the homepage
json.data.children.reduce(function(x,y) { return x+y.data.downs; }, 0)

Now that the world hasn’t ended, the JSON is your oyster, go out and code!

comments powered by Disqus

Peter Coles

Peter Coles

is a software engineer who lives in NYC, works at Ringly, and blogs here.
More about Peter »

github · soundcloud · @lethys · rss

It’s time to get big money out of politics. Join the kick-started campaign to put government back in the hands of the people. Pledge mayday.us now