diff --git a/src/document.rs b/src/document.rs index f4e2cb7d..36e7f0ca 100644 --- a/src/document.rs +++ b/src/document.rs @@ -672,19 +672,28 @@ impl Document { self.add_value(field_name, bytes); } - /// Add a bytes value to the document. + /// Add a JSON value to the document. /// /// Args: /// field_name (str): The field for which we are adding the bytes. - /// value (str): The json object that will be added to the document. + /// value (str | Dict[str, Any]): The JSON object that will be added + /// to the document. /// - /// Raises a ValueError if the json is invalid. - fn add_json(&mut self, field_name: String, json: &str) -> PyResult<()> { - let json_object: serde_json::Value = - serde_json::from_str(json).map_err(to_pyerr)?; - self.add_value(field_name, json_object); - - Ok(()) + /// Raises a ValueError if the JSON is invalid. + fn add_json(&mut self, field_name: String, value: &PyAny) -> PyResult<()> { + type JsonMap = serde_json::Map; + + if let Ok(json_str) = value.extract::<&str>() { + let json_map: JsonMap = + serde_json::from_str(json_str).map_err(to_pyerr)?; + self.add_value(field_name, json_map); + Ok(()) + } else if let Ok(json_map) = pythonize::depythonize::(value) { + self.add_value(field_name, json_map); + Ok(()) + } else { + Err(to_pyerr("Invalid JSON object. Expected valid JSON string or Dict[str, Any].")) + } } /// Returns the number of added fields that have been added to the document diff --git a/tests/tantivy_test.py b/tests/tantivy_test.py index 5e409207..6b4c2b40 100644 --- a/tests/tantivy_test.py +++ b/tests/tantivy_test.py @@ -786,12 +786,12 @@ def test_query_from_json_field(self): doc = Document() doc.add_json( "attributes", - """{ - "order":1.2, + { + "order": 1.2, "target": "submit-button", "cart": {"product_id": 133}, - "description": "das keyboard" - }""", + "description": "das keyboard", + }, ) writer.add_document(doc)