@@ -686,6 +686,73 @@ def json_dumps(obj: Any, **kwargs) -> str:
686686 return json .dumps (obj , ** kwargs )
687687
688688
689+ def _orjson_default (obj : Any ) -> Any :
690+ """Handle custom types for orjson serialization.
691+
692+ Args:
693+ obj: The object to serialize.
694+
695+ Returns:
696+ A JSON-serializable representation of the object.
697+
698+ Raises:
699+ TypeError: If the object is not JSON serializable.
700+ """
701+ from reflex .utils import serializers
702+
703+ result = serializers .serialize (obj )
704+ if result is not None :
705+ return result
706+ msg = f"Object of type { type (obj ).__name__ } is not JSON serializable"
707+ raise TypeError (msg )
708+
709+
710+ def json_dumps_fast (obj : Any ) -> str :
711+ """Fast JSON serialization using orjson when available.
712+
713+ This function provides a faster alternative to json_dumps() by using
714+ the orjson library (written in Rust) when it's installed. Falls back
715+ to the standard json_dumps() if orjson is not available.
716+
717+ Args:
718+ obj: The object to serialize to JSON.
719+
720+ Returns:
721+ A JSON string representation of the object.
722+ """
723+ try :
724+ import orjson
725+
726+ return orjson .dumps (
727+ obj ,
728+ default = _orjson_default ,
729+ option = orjson .OPT_NON_STR_KEYS | orjson .OPT_SERIALIZE_NUMPY ,
730+ ).decode ("utf-8" )
731+ except ImportError :
732+ return json_dumps (obj )
733+
734+
735+ def json_loads_fast (data : str | bytes ) -> Any :
736+ """Fast JSON deserialization using orjson when available.
737+
738+ This function provides a faster alternative to json.loads() by using
739+ the orjson library (written in Rust) when it's installed. Falls back
740+ to the standard json.loads() if orjson is not available.
741+
742+ Args:
743+ data: The JSON string or bytes to deserialize.
744+
745+ Returns:
746+ The deserialized Python object.
747+ """
748+ try :
749+ import orjson
750+
751+ return orjson .loads (data )
752+ except ImportError :
753+ return json .loads (data )
754+
755+
689756def collect_form_dict_names (form_dict : dict [str , Any ]) -> dict [str , Any ]:
690757 """Collapse keys with consecutive suffixes into a single list value.
691758
0 commit comments