19 Json to_json(
const py::handle& obj)
25 else if (py::isinstance<py::bool_>(obj))
27 return obj.cast<
bool>();
29 else if (py::isinstance<py::int_>(obj))
31 return obj.cast<
int>();
33 else if (py::isinstance<py::float_>(obj))
35 return obj.cast<
double>();
37 else if (py::isinstance<py::str>(obj))
39 return obj.cast<std::string>();
41 else if (py::isinstance<py::tuple>(obj) || py::isinstance<py::list>(obj))
45 for (
const py::handle& value : obj)
47 out.push_back(to_json(value));
52 else if (py::isinstance<py::dict>(obj))
56 for (
const py::handle& key : obj)
58 out[key.cast<std::string>()] = to_json(obj[key]);
67 return Json::parse(py::cast<std::string>(
68 py::module::import(
"json").attr(
"dumps")(py::cast<py::object>(obj))));
73 "to_json not implemented for this type of object: "+ obj.cast<std::string>());
78 py::object from_json(
const Json& j)
84 else if (j.is_boolean())
86 return py::bool_(j.get<
bool>());
88 else if (j.is_number_integer())
90 return py::int_(j.get<
int>());
92 else if (j.is_number_float())
94 return py::float_(j.get<
double>());
96 else if (j.is_string())
98 return py::str(j.get<std::string>());
100 else if (j.is_array())
104 for (
const auto& el : j)
106 obj.attr(
"append")(from_json(el));
115 for (Json::const_iterator it = j.cbegin(); it != j.cend(); ++it)
117 obj[py::str(it.key())] = from_json(it.value());
130 value = impl::to_json(src);
141 Json src, return_value_policy, handle)
143 return impl::from_json(src).release();
To bind Json to Python, a custom type caster of pybind11* is required.
static handle cast(Json src, return_value_policy, handle)
Casting a Json object from C++ to Python.
nlohmann::json Json
Json is an alias for nlohmann::json.
This file includes nlohmann/json and defines an alias for a JSON class.
bool load(handle src, bool)
Loading a Json object from Python to C++.
void runtime_error(const Str &msg)
Raise (for Python) and throw (for C++) a runtime error.
This file includes pybind11 and defines an alias for the namespace pybind11.