@@ -813,6 +813,59 @@ def _dfs(obj):
813
813
def from_primitive (cls : Type [RawPlutusData ], value : CBORTag ) -> RawPlutusData :
814
814
return cls (value )
815
815
816
+ @classmethod
817
+ def from_dict (cls : Type [RawPlutusData ], data : dict ) -> RawPlutusData :
818
+ """Convert a dictionary to RawPlutusData
819
+
820
+ Args:
821
+ data (dict): A dictionary.
822
+
823
+ Returns:
824
+ RawPlutusData: Restored RawPlutusData.
825
+ """
826
+
827
+ def _dfs (obj ):
828
+ if isinstance (obj , dict ):
829
+ if "constructor" in obj :
830
+ converted_fields = []
831
+ for f in obj ["fields" ]:
832
+ converted_fields .append (_dfs (f ))
833
+ tag = get_tag (obj ["constructor" ])
834
+ if tag is None :
835
+ return CBORTag (102 , [obj ["constructor" ], IndefiniteList (converted_fields )])
836
+ else :
837
+ return CBORTag (tag , converted_fields )
838
+ elif "map" in obj :
839
+ return {_dfs (pair ["k" ]): _dfs (pair ["v" ]) for pair in obj ["map" ]}
840
+ elif "int" in obj :
841
+ return obj ["int" ]
842
+ elif "bytes" in obj :
843
+ if len (obj ["bytes" ]) > 64 :
844
+ return ByteString (bytes .fromhex (obj ["bytes" ]))
845
+ else :
846
+ return bytes .fromhex (obj ["bytes" ])
847
+ elif "list" in obj :
848
+ return IndefiniteList ([_dfs (item ) for item in obj ["list" ]])
849
+ else :
850
+ raise DeserializeException (f"Unexpected data structure: { obj } " )
851
+ else :
852
+ raise TypeError (f"Unexpected data type: { type (obj )} " )
853
+
854
+ return cls (_dfs (data ))
855
+
856
+ @classmethod
857
+ def from_json (cls : Type [RawPlutusData ], data : str ) -> RawPlutusData :
858
+ """Restore a json encoded string to a RawPlutusData.
859
+
860
+ Args:
861
+ data (str): An encoded json string.
862
+
863
+ Returns:
864
+ RawPlutusData: The restored RawPlutusData.
865
+ """
866
+ obj = json .loads (data )
867
+ return cls .from_dict (obj )
868
+
816
869
def __deepcopy__ (self , memo ):
817
870
return self .__class__ .from_cbor (self .to_cbor_hex ())
818
871
0 commit comments