Skip to content

Commit adfdae0

Browse files
authored
Support passing dict to add JSON field (#158)
1 parent 1116290 commit adfdae0

File tree

2 files changed

+22
-13
lines changed

2 files changed

+22
-13
lines changed

src/document.rs

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -674,19 +674,28 @@ impl Document {
674674
self.add_value(field_name, bytes);
675675
}
676676

677-
/// Add a bytes value to the document.
677+
/// Add a JSON value to the document.
678678
///
679679
/// Args:
680680
/// 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.
682683
///
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+
}
690699
}
691700

692701
/// Returns the number of added fields that have been added to the document

tests/tantivy_test.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -786,12 +786,12 @@ def test_query_from_json_field(self):
786786
doc = Document()
787787
doc.add_json(
788788
"attributes",
789-
"""{
790-
"order":1.2,
789+
{
790+
"order": 1.2,
791791
"target": "submit-button",
792792
"cart": {"product_id": 133},
793-
"description": "das keyboard"
794-
}""",
793+
"description": "das keyboard",
794+
},
795795
)
796796

797797
writer.add_document(doc)

0 commit comments

Comments
 (0)