Created
March 28, 2011 01:37
-
-
Save omarish/889852 to your computer and use it in GitHub Desktop.
Parse any JSON data structure into suitable javascript objects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time, math | |
def dt_handler(obj): | |
if isinstance(obj, datetime) or isinstance(obj, date): | |
v = math.floor(time.mktime(obj.timetuple())) | |
return "DATE(%d)" % v | |
else: return repr(obj) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<script type="text/javascript" src="http://documentcloud.github.com/underscore/underscore-min.js"></script> | |
<script type="text/javascript"> | |
var transform = function(val) { | |
if(val.indexOf('DATE') > -1) { | |
seconds = val.substring(5, val.length - 1); | |
d = new Date(); d.setTime(seconds*1000); | |
return d; | |
} | |
else { | |
return val; | |
} | |
}; | |
var transformNode = function(node) { | |
node.key = transform(node.key); | |
if(typeof node.value === "string") { | |
node.value = transform(node.value); | |
} else if(typeof node.value === "object") { | |
node.value = _.map(node.value, transformNode); | |
} | |
return node; | |
}; | |
var parse = function(nodes) { | |
return _.map(nodes, transformNode); | |
}; | |
result = [ | |
{ | |
'key': 'DATE(1998966400)', | |
'value': 1 | |
}, | |
{ | |
'key': 'DATE(1298966500)', | |
'value': 2 | |
}, | |
{ | |
'key': 'DATE(1398066400)', | |
'value': [ | |
{ | |
'key': 'DATE(1298966500)', | |
'value': 2 | |
} | |
] | |
} | |
]; | |
console.warn("Input:", result); | |
parsed = parse(result); | |
console.warn("Parsed:", parsed); | |
</script> | |
</head> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import simplejson as json | |
from handler import dt_handler | |
envelope = {} # this is where your data comes from. | |
json.dumps(envelope, default=dt_handler), mimetype="application/json") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment