Support passing dict to add JSON field (#158)

master
Chris Tam 2023-11-21 14:44:21 -05:00 committed by GitHub
parent 111629006b
commit adfdae0e64
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 12 deletions

View File

@ -674,19 +674,28 @@ impl Document {
self.add_value(field_name, bytes); self.add_value(field_name, bytes);
} }
/// Add a bytes value to the document. /// Add a JSON value to the document.
/// ///
/// Args: /// Args:
/// field_name (str): The field for which we are adding the bytes. /// 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. /// Raises a ValueError if the JSON is invalid.
fn add_json(&mut self, field_name: String, json: &str) -> PyResult<()> { fn add_json(&mut self, field_name: String, value: &PyAny) -> PyResult<()> {
let json_object: serde_json::Value = type JsonMap = serde_json::Map<String, serde_json::Value>;
serde_json::from_str(json).map_err(to_pyerr)?;
self.add_value(field_name, json_object);
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(()) Ok(())
} else if let Ok(json_map) = pythonize::depythonize::<JsonMap>(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 /// Returns the number of added fields that have been added to the document

View File

@ -786,12 +786,12 @@ class TestJsonField:
doc = Document() doc = Document()
doc.add_json( doc.add_json(
"attributes", "attributes",
"""{ {
"order":1.2, "order": 1.2,
"target": "submit-button", "target": "submit-button",
"cart": {"product_id": 133}, "cart": {"product_id": 133},
"description": "das keyboard" "description": "das keyboard",
}""", },
) )
writer.add_document(doc) writer.add_document(doc)