Skip to content

Commit

Permalink
add from_json
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelcolvin committed Nov 2, 2023
1 parent 7c978e2 commit cb02b30
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
17 changes: 17 additions & 0 deletions python/pydantic_core/_pydantic_core.pyi
Expand Up @@ -41,6 +41,7 @@ __all__ = [
'PydanticUndefinedType',
'Some',
'to_json',
'from_json',
'to_jsonable_python',
'list_all_errors',
'TzInfo',
Expand Down Expand Up @@ -384,6 +385,22 @@ def to_json(
JSON bytes.
"""

def from_json(data: str | bytes | bytearray) -> Any:
"""
Deserialize JSON data to a Python object.
This is effectively a faster version of [`json.loads()`][json.loads].
Arguments:
data: The JSON data to deserialize.
Raises:
ValueError: If deserialization fails.
Returns:
The deserialized Python object.
"""

def to_jsonable_python(
value: Any,
*,
Expand Down
16 changes: 16 additions & 0 deletions src/lib.rs
Expand Up @@ -4,6 +4,8 @@ extern crate core;

use std::sync::OnceLock;

use pyo3::exceptions::PyTypeError;
use pyo3::types::{PyByteArray, PyBytes, PyString};
use pyo3::{prelude::*, sync::GILOnceCell};

// parse this first to get access to the contained macro
Expand Down Expand Up @@ -35,6 +37,19 @@ pub use serializers::{
};
pub use validators::{validate_core_schema, PySome, SchemaValidator};

#[pyfunction]
pub fn from_json(py: Python, obj: &PyAny) -> PyResult<PyObject> {
if let Ok(py_bytes) = obj.downcast::<PyBytes>() {
jiter::python_parse(py, py_bytes.as_bytes())
} else if let Ok(py_str) = obj.downcast::<PyString>() {
jiter::python_parse(py, py_str.to_str()?.as_bytes())
} else if let Ok(py_byte_array) = obj.downcast::<PyByteArray>() {
jiter::python_parse(py, &py_byte_array.to_vec())
} else {
Err(PyTypeError::new_err("Expected bytes, bytearray or str"))
}
}

pub fn get_pydantic_core_version() -> &'static str {
static PYDANTIC_CORE_VERSION: OnceLock<String> = OnceLock::new();

Expand Down Expand Up @@ -94,6 +109,7 @@ fn _pydantic_core(py: Python, m: &PyModule) -> PyResult<()> {
m.add_class::<SchemaSerializer>()?;
m.add_class::<TzInfo>()?;
m.add_function(wrap_pyfunction!(to_json, m)?)?;
m.add_function(wrap_pyfunction!(from_json, m)?)?;
m.add_function(wrap_pyfunction!(to_jsonable_python, m)?)?;
m.add_function(wrap_pyfunction!(list_all_errors, m)?)?;
m.add_function(wrap_pyfunction!(validate_core_schema, m)?)?;
Expand Down

0 comments on commit cb02b30

Please sign in to comment.