Skip to content

Commit

Permalink
feat(Python bindings): Add utilty functions for converting to/from JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
nokome committed Jul 24, 2019
1 parent 2863a49 commit b4c8aa4
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
32 changes: 32 additions & 0 deletions python/util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import json
import .types
from .types import Node, Thing

# TODO: Use Entity instead of Thing
# When https://github.com/stencila/schema/issues/96 is done

def toDict(node: Thing) -> dict:
"""Convert a Thing node to a dictionary"""
node_dict = {
"type": node.__class__.__name__
}
node_dict.update(node.__dict__)
return node_dict

def fromDict(node_dict: dict) -> Thing:
"""Convert a dictionary to a Thing node"""
if "type" in node_dict:
class_ = getattr(types, node_dict["type"])
return class_(**node_dict)
else:
return node_dict

def toJSON(node: Node) -> str:
"""Convert a node to JSON"""
return json.dumps(node, default=toDict, indent=2)

def fromJSON(json: str) -> Node:
"""Convert JSON to a Node"""
node = json.loads(json)
if isinstance(node, dict): return fromDict(node)
else return node
2 changes: 2 additions & 0 deletions tests/article.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from python.types import Article, Person, Paragraph
from python.util import toJSON

article = Article(
title='',
Expand All @@ -12,3 +13,4 @@
]
)

print(toJSON(article))

0 comments on commit b4c8aa4

Please sign in to comment.