From 2453843850c54c3b0ab3174762f808aeabec1af9 Mon Sep 17 00:00:00 2001 From: Eckhart Arnold Date: Fri, 8 Mar 2019 07:54:39 +0100 Subject: [PATCH] - json serialization of Nodes done --- DHParser/error.py | 2 +- DHParser/syntaxtree.py | 31 ++++++++++++++++++++++++------- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/DHParser/error.py b/DHParser/error.py index fb2c36e2..f45184f6 100644 --- a/DHParser/error.py +++ b/DHParser/error.py @@ -143,7 +143,7 @@ class Error: def from_json_obj(self, json_obj: Dict) -> Error: """Convert a json object representing an Error object back into an Error object. Raises a ValueError, if json_obj does not represent - an error object""" + an Error object""" if json_obj.get('__class__', '') != 'DHParser.Error': raise ValueError('JSON object: ' + str(json_obj) + ' does not represent an Error object.') diff --git a/DHParser/syntaxtree.py b/DHParser/syntaxtree.py index 0022cb38..fdb38d94 100644 --- a/DHParser/syntaxtree.py +++ b/DHParser/syntaxtree.py @@ -749,17 +749,34 @@ class Node: # (collections.abc.Sized): Base class omitted for cython-compatibil def to_json_obj(self) -> Dict: - return { '__class__': 'DHParser.Nose', - 'content': [ self.tag_name, - [child.to_json_obj() for child in self.children] if self.children - else self.result_, - self._pos, - self._xmlattr if self.attr_active() else None ] } + """Seralize a node or tree as json-object""" + return { '__class__': 'DHParser.Node', + 'data': [ self.tag_name, + [child.to_json_obj() for child in self.children] if self.children + else str(self.result_), + self._pos, + self._xmlattr if self.attr_active() else None ] } @static def from_json_obj(self, json_obj: Dict) -> Error: - pass + """Convert a json object representing a node (or tree) back into a + Node object. Raises a ValueError, if `json_obj` does not represent + a node.""" + if json_obj.get('__class__', '') != 'DHParser.Node': + raise ValueError('JSON object: ' + str(json_obj) + + ' does not represent a Node object.') + tag_name, result, pos, attr = json_obj['data'] + if isinstance(str): + leafhint = True + else: + leafhint = False + result = tuple(Node.from_json_obj(child) for child in result) + node = Node(tag_name, result, leafhint) + node._pos = pos + if attr: + node.attr = attr + return node def serialize(node: Node, how: str='default') -> str: -- GitLab