Python: Make simplejson.dumps output raw Javascript code

class JSRaw(int):
    """Hack to allow including raw Javascript code in simplejson.dumps
    output. Objects of this sort are dumped as raw strings.
    """
    def __new__(self, string):
        instance = int.__new__(self, 0)
        instance.string = string
        return instance
    def __repr__(self):
        return self.string
    def __unicode__(self):
        return self.string
    def __str__(self):
        return self.string

Example:

s = jsondumps({
    'series': data,
    'yAxis': {
        'labels': {
            'formatter': JSRaw("""
                function() {
                    return (this.value > 0 ? '+' : '') + this.value + '%';
                }""")
        }
    }
})

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s