Skip to content

Instantly share code, notes, and snippets.

@omarish
Created March 28, 2011 01:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omarish/889852 to your computer and use it in GitHub Desktop.
Save omarish/889852 to your computer and use it in GitHub Desktop.
Parse any JSON data structure into suitable javascript objects.
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)
<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>
#!/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