@@ -449,6 +449,26 @@ def get_tag(constr_id: int) -> Optional[int]:
449449 return None
450450
451451
452+ def get_constructor_id_and_fields (
453+ raw_tag : CBORTag ,
454+ ) -> typing .Tuple [int , typing .List [Any ]]:
455+ tag = raw_tag .tag
456+ if tag == 102 :
457+ if len (raw_tag .value ) != 2 :
458+ raise DeserializeException (
459+ f"Expect the length of value to be exactly 2, got { len (raw_tag .value )} instead."
460+ )
461+ return raw_tag .value [0 ], raw_tag .value [1 ]
462+ else :
463+ if 121 <= tag < 128 :
464+ constr = tag - 121
465+ elif 1280 <= tag < 1536 :
466+ constr = tag - 1280 + 7
467+ else :
468+ raise DeserializeException (f"Unexpected tag for RawPlutusData: { tag } " )
469+ return constr , raw_tag .value
470+
471+
452472def id_map (cls , skip_constructor = False ):
453473 """
454474 Constructs a unique representation of a PlutusData type definition.
@@ -610,6 +630,10 @@ def _dfs(obj):
610630 "constructor" : obj .CONSTR_ID ,
611631 "fields" : [_dfs (getattr (obj , f .name )) for f in fields (obj )],
612632 }
633+ elif isinstance (obj , RawPlutusData ):
634+ return obj .to_json ()
635+ elif isinstance (obj , RawCBOR ):
636+ return RawPlutusData .from_cbor (obj .cbor ).to_json ()
613637 else :
614638 raise TypeError (f"Unexpected type { type (obj )} " )
615639
@@ -765,6 +789,25 @@ def _dfs(obj):
765789
766790 return _dfs (self .data )
767791
792+ def to_json (self , ** kwargs ) -> str :
793+ def _dfs (obj ):
794+ if isinstance (obj , int ):
795+ return {"int" : obj }
796+ elif isinstance (obj , bytes ):
797+ return {"bytes" : obj .hex ()}
798+ elif isinstance (obj , ByteString ):
799+ return {"bytes" : obj .value .hex ()}
800+ elif isinstance (obj , IndefiniteList ) or isinstance (obj , list ):
801+ return {"list" : [_dfs (item ) for item in obj ]}
802+ elif isinstance (obj , dict ):
803+ return {"map" : [{"v" : _dfs (v ), "k" : _dfs (k )} for k , v in obj .items ()]}
804+ elif isinstance (obj , CBORTag ):
805+ constructor , fields = get_constructor_id_and_fields (obj )
806+ return {"constructor" : constructor , "fields" : [_dfs (f ) for f in fields ]}
807+ raise TypeError (f"Unexpected type { type (obj )} " )
808+
809+ return json .dumps (_dfs (self .to_primitive ()), ** kwargs )
810+
768811 @classmethod
769812 @limit_primitive_type (CBORTag )
770813 def from_primitive (cls : Type [RawPlutusData ], value : CBORTag ) -> RawPlutusData :
0 commit comments