-
-
Save voidlizard/6547018325a637f83208 to your computer and use it in GitHub Desktop.
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
# -*- coding: utf-8 -*- | |
def dump_atom( a ): | |
if type(a) == int or type(a) == long: | |
return str(a) | |
elif type(a) == bool: | |
return str(a).lower() | |
elif a is None: | |
return 'null' | |
else: # type(a) == str or type(a) == unicode: | |
return "'" + str(a).replace("\\","\\\\").replace("'","\\'") + "'" | |
def dump_element( el ): | |
if hasattr(el, "__dict__"): | |
return dump_object(el) | |
elif type(el) == dict: | |
return dump_dict(el) | |
elif hasattr(el, "__iter__"): | |
return dump_sequence(el) | |
return dump_atom(el) | |
def dump_object( obj ): | |
return dump_dict(obj.__dict__) | |
def dump_sequence( seq ): | |
return '[' + ', '.join( dump_element(x) for x in seq ) + ']' | |
def dump_dict( d ): | |
return '{' + ', '.join( ("'%s' : %s"%(k, dump_element(v)) for k,v in d.iteritems()) ) + '}' | |
def dump_assignment( left, right ): | |
if left is not None: | |
return left + ' = ' + dump_element( right ) | |
return dump_element( right ) | |
class JSON_Dumper(object): | |
def __init__(self, root=None): | |
self.root = root | |
def dump_dict(self, **objects): | |
return dump_assignment( self.root, objects ) | |
def dump_object(self, x): | |
return dump_assignment( self.root, x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment