Convert JSON value to Python object
(value: &serde_json::Value, py: Python<'_>)
| 823 | |
| 824 | /// Convert JSON value to Python object |
| 825 | fn json_to_python_value(value: &serde_json::Value, py: Python<'_>) -> PyResult<PyObject> { |
| 826 | match value { |
| 827 | serde_json::Value::Null => Ok(py.None()), |
| 828 | serde_json::Value::Bool(b) => { |
| 829 | let py_bool = b.into_pyobject(py)?; |
| 830 | Ok( |
| 831 | <pyo3::Bound<'_, pyo3::types::PyBool> as Clone>::clone(&py_bool) |
| 832 | .into_any() |
| 833 | .unbind(), |
| 834 | ) |
| 835 | } |
| 836 | serde_json::Value::Number(n) => { |
| 837 | if let Some(i) = n.as_i64() { |
| 838 | Ok(i.into_pyobject(py)?.into_any().unbind()) |
| 839 | } else if let Some(f) = n.as_f64() { |
| 840 | Ok(f.into_pyobject(py)?.into_any().unbind()) |
| 841 | } else { |
| 842 | Ok(n.to_string().into_pyobject(py)?.into_any().unbind()) |
| 843 | } |
| 844 | } |
| 845 | serde_json::Value::String(s) => Ok(s.into_pyobject(py)?.into_any().unbind()), |
| 846 | serde_json::Value::Array(arr) => { |
| 847 | let py_list = pyo3::types::PyList::empty(py); |
| 848 | for item in arr { |
| 849 | let py_item = json_to_python_value(item, py)?; |
| 850 | py_list.append(py_item)?; |
| 851 | } |
| 852 | Ok(py_list.into_pyobject(py)?.into_any().unbind()) |
| 853 | } |
| 854 | serde_json::Value::Object(obj) => { |
| 855 | let py_dict = pyo3::types::PyDict::new(py); |
| 856 | for (key, val) in obj { |
| 857 | let py_val = json_to_python_value(val, py)?; |
| 858 | py_dict.set_item(key, py_val)?; |
| 859 | } |
| 860 | Ok(py_dict.into_pyobject(py)?.into_any().unbind()) |
| 861 | } |
| 862 | } |
| 863 | } |
| 864 | |
| 865 | /// Execute a tool from the registry by name with given arguments |
| 866 | #[pyfunction] |
no test coverage detected