@@ -674,19 +674,28 @@ impl Document {
674
674
self . add_value ( field_name, bytes) ;
675
675
}
676
676
677
- /// Add a bytes value to the document.
677
+ /// Add a JSON value to the document.
678
678
///
679
679
/// Args:
680
680
/// field_name (str): The field for which we are adding the bytes.
681
- /// value (str): The json object that will be added to the document.
681
+ /// value (str | Dict[str, Any]): The JSON object that will be added
682
+ /// to the document.
682
683
///
683
- /// Raises a ValueError if the json is invalid.
684
- fn add_json ( & mut self , field_name : String , json : & str ) -> PyResult < ( ) > {
685
- let json_object: serde_json:: Value =
686
- serde_json:: from_str ( json) . map_err ( to_pyerr) ?;
687
- self . add_value ( field_name, json_object) ;
688
-
689
- Ok ( ( ) )
684
+ /// Raises a ValueError if the JSON is invalid.
685
+ fn add_json ( & mut self , field_name : String , value : & PyAny ) -> PyResult < ( ) > {
686
+ type JsonMap = serde_json:: Map < String , serde_json:: Value > ;
687
+
688
+ if let Ok ( json_str) = value. extract :: < & str > ( ) {
689
+ let json_map: JsonMap =
690
+ serde_json:: from_str ( json_str) . map_err ( to_pyerr) ?;
691
+ self . add_value ( field_name, json_map) ;
692
+ Ok ( ( ) )
693
+ } else if let Ok ( json_map) = pythonize:: depythonize :: < JsonMap > ( value) {
694
+ self . add_value ( field_name, json_map) ;
695
+ Ok ( ( ) )
696
+ } else {
697
+ Err ( to_pyerr ( "Invalid JSON object. Expected valid JSON string or Dict[str, Any]." ) )
698
+ }
690
699
}
691
700
692
701
/// Returns the number of added fields that have been added to the document
0 commit comments