33import json
44import uuid
55from importlib .resources import files
6+ from typing import Any , Union
67
78from IPython .display import HTML
89
@@ -40,10 +41,30 @@ def __init__(self) -> None:
4041 with screenshot_path .open ("r" , encoding = "utf-8" ) as file :
4142 self .screenshot_svg = file .read ()
4243
43- def unsupported_field_type_error (self , e : TypeError , entity : str ) -> Exception :
44- if "not JSON serializable" in str (e ):
45- return ValueError (f"A field of a { entity } object is not supported: { str (e )} " )
46- return e
44+ @staticmethod
45+ def _serialize_entity (entity : Union [Node , Relationship ]) -> dict [str , Any ]:
46+ try :
47+ entity_dict = entity .to_dict ()
48+ json .dumps (entity_dict )
49+ return entity_dict
50+ except TypeError :
51+ props_as_strings = {}
52+ for k , v in entity_dict ["properties" ].items ():
53+ try :
54+ json .dumps (v )
55+ except TypeError :
56+ props_as_strings [k ] = str (v )
57+ entity_dict ["properties" ].update (props_as_strings )
58+
59+ try :
60+ json .dumps (entity_dict )
61+ return entity_dict
62+ except TypeError as e :
63+ # This should never happen anymore, but just in case
64+ if "not JSON serializable" in str (e ):
65+ raise ValueError (f"A field of a { type (entity ).__name__ } object is not supported: { str (e )} " )
66+ else :
67+ raise e
4768
4869 def render (
4970 self ,
@@ -54,14 +75,8 @@ def render(
5475 height : str ,
5576 show_hover_tooltip : bool ,
5677 ) -> HTML :
57- try :
58- nodes_json = json .dumps ([node .to_dict () for node in nodes ])
59- except TypeError as e :
60- raise self .unsupported_field_type_error (e , "node" )
61- try :
62- rels_json = json .dumps ([rel .to_dict () for rel in relationships ])
63- except TypeError as e :
64- raise self .unsupported_field_type_error (e , "relationship" )
78+ nodes_json = json .dumps ([self ._serialize_entity (node ) for node in nodes ])
79+ rels_json = json .dumps ([self ._serialize_entity (rel ) for rel in relationships ])
6580
6681 render_options_json = json .dumps (render_options .to_dict ())
6782 container_id = str (uuid .uuid4 ())
0 commit comments