From 388f311d154947a169543db0e25dcda35169e195 Mon Sep 17 00:00:00 2001 From: Victor Villar Date: Sat, 10 Apr 2021 03:26:13 +0200 Subject: [PATCH] Add python iterables to to_json conversion method (#1217) --- src/framework/pybind_json.hpp | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/framework/pybind_json.hpp b/src/framework/pybind_json.hpp index 505fce8d99..4bcb9a7e66 100755 --- a/src/framework/pybind_json.hpp +++ b/src/framework/pybind_json.hpp @@ -109,6 +109,8 @@ json_t numpy_to_json_2d(py::array_t arr); template json_t numpy_to_json_3d(py::array_t arr); +json_t iterable_to_json_list(const py::handle& obj); + } //end namespace JSON /******************************************************************************* @@ -208,6 +210,14 @@ json_t JSON::numpy_to_json(py::array_t arr) { return tbr; } +json_t JSON::iterable_to_json_list(const py::handle& obj){ + json_t js = nl::json::array(); + for (py::handle value: obj) { + js.push_back(value); + } + return js; +} + void std::to_json(json_t &js, const py::handle &obj) { static py::object PyNoiseModel = py::module::import("qiskit.providers.aer.noise.noise_model").attr("NoiseModel"); static py::object PyQasmQobj = py::module::import("qiskit.qobj.qasm_qobj").attr("QasmQobj"); @@ -220,10 +230,7 @@ void std::to_json(json_t &js, const py::handle &obj) { } else if (py::isinstance(obj)) { js = obj.cast(); } else if (py::isinstance(obj) || py::isinstance(obj)) { - js = nl::json::array(); - for (py::handle value: obj) { - js.push_back(value); - } + js = JSON::iterable_to_json_list(obj); } else if (py::isinstance(obj)) { for (auto item : py::cast(obj)) { js[item.first.cast()] = item.second; @@ -255,6 +262,8 @@ void std::to_json(json_t &js, const py::handle &obj) { } else if ( type_str == "" || type_str == "" ) { js = obj.cast(); + } else if ( py::isinstance(obj) ){ // last one to avoid intercepting numpy arrays, etc + js = JSON::iterable_to_json_list(obj); } else { throw std::runtime_error("to_json not implemented for this type of object: " + std::string(py::str(obj.get_type()))); }