Skip to content

Commit f4346e7

Browse files
committed
Move functionality to add_json_from_dict()
1 parent 9653115 commit f4346e7

File tree

2 files changed

+29
-20
lines changed

2 files changed

+29
-20
lines changed

src/document.rs

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -672,28 +672,37 @@ impl Document {
672672
self.add_value(field_name, bytes);
673673
}
674674

675-
/// Add a bytes value to the document.
675+
/// Add a JSON value to the document.
676676
///
677677
/// Args:
678-
/// field_name (str): The field for which we are adding the bytes.
679-
/// value (str | Dict[str, Any]): The json object that will be added
680-
/// to the document.
678+
/// field_name (str): The field for which we are adding the JSON.
679+
/// value (str): The JSON object that will be added to the document.
681680
///
682-
/// Raises a ValueError if the json is invalid.
683-
fn add_json(&mut self, field_name: String, value: &PyAny) -> PyResult<()> {
684-
type JsonMap = serde_json::Map<String, serde_json::Value>;
685-
686-
if let Ok(json_str) = value.extract::<&str>() {
687-
let json_map: JsonMap =
688-
serde_json::from_str(json_str).map_err(to_pyerr)?;
689-
self.add_value(field_name, json_map);
690-
Ok(())
691-
} else if let Ok(json_map) = pythonize::depythonize::<JsonMap>(value) {
692-
self.add_value(field_name, json_map);
693-
Ok(())
694-
} else {
695-
Err(to_pyerr("Invalid JSON object. Expected valid JSON string or Dict[str, Any]."))
696-
}
681+
/// Raises a ValueError if the JSON is invalid.
682+
fn add_json(&mut self, field_name: String, value: &str) -> PyResult<()> {
683+
let json_map: serde_json::Map<String, serde_json::Value> =
684+
serde_json::from_str(value).map_err(to_pyerr)?;
685+
self.add_value(field_name, json_map);
686+
Ok(())
687+
}
688+
689+
/// Add a JSON value to the document from a dictionary of values.
690+
///
691+
/// Args:
692+
/// field_name (str): The field for which we are adding the JSON.
693+
/// value (Dict[str, Any]): The JSON object that will be added to the
694+
/// document.
695+
///
696+
/// Raises a ValueError if the JSON is invalid.
697+
fn add_json_from_dict(
698+
&mut self,
699+
field_name: String,
700+
value: &PyDict,
701+
) -> PyResult<()> {
702+
let json_map: serde_json::Map<String, serde_json::Value> =
703+
pythonize::depythonize(value).map_err(to_pyerr)?;
704+
self.add_value(field_name, json_map);
705+
Ok(())
697706
}
698707

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

tests/tantivy_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -784,7 +784,7 @@ def test_query_from_json_field(self):
784784
writer.add_document(doc)
785785

786786
doc = Document()
787-
doc.add_json(
787+
doc.add_json_from_dict(
788788
"attributes",
789789
{
790790
"order": 1.2,

0 commit comments

Comments
 (0)