Created
November 23, 2010 21:17
-
-
Save glimberg/712554 to your computer and use it in GitHub Desktop.
test for a tree like structure encoded & decoded by jsonpickle
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 jsonpickle | |
class Node(object): | |
def __init__(self, name): | |
self._name = name | |
self._children = [] | |
self._parent = None | |
def add_child(self, child, index=-1): | |
if index == -1: | |
index = len(self._children) | |
self._children.insert(index, child) | |
child._parent = self | |
class Document(Node): | |
def __init__(self, name): | |
Node.__init__(self, name) | |
def __str__(self): | |
ret_str ='Document "%s"\n' %self._name | |
for c in self._children: | |
ret_str += repr(c) | |
return ret_str | |
def __repr__(self): | |
return self.__str__() | |
class Section(Node): | |
def __init__(self, name): | |
Node.__init__(self, name) | |
def __str__(self): | |
ret_str = 'Section "%s", parent: "%s"\n' % (self._name, self._parent._name) | |
for c in self._children: | |
ret_str += repr(c) | |
return ret_str | |
def __repr__(self): | |
return self.__str__() | |
class Question(Node): | |
def __init__(self, name): | |
Node.__init__(self, name) | |
def __str__(self): | |
return 'Question "%s", parent: "%s"\n' % (self._name, self._parent._name) | |
def __repr__(self): | |
return self.__str__() | |
if __name__ == '__main__': | |
# set up the cyclical structure | |
document = Document('My Document') | |
section1 = Section('Section 1') | |
section2 = Section('Section 2') | |
question1 = Question('Question 1') | |
question2 = Question('Question 2') | |
question3 = Question('Question 3') | |
question4 = Question('Question 4') | |
document.add_child(section1) | |
document.add_child(section2) | |
section1.add_child(question1) | |
section1.add_child(question2) | |
section2.add_child(question3) | |
section2.add_child(question4) | |
print "Original Document Structure: " | |
print document | |
output_file = open(path, 'w') | |
jsonpickle.set_encoder_options('json', indent=2) | |
pickled = jsonpickle.encode(document) | |
unpickled = jsonpickle.decode(pickled) | |
print "Document Structure after jsonpickle.decode()" | |
print unpickled |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment