Shamrock 2025.10.0
Astrophysical Code
Loading...
Searching...
No Matches
shamrock_json_to_py_json.hpp
Go to the documentation of this file.
1// -------------------------------------------------------//
2//
3// SHAMROCK code for hydrodynamics
4// Copyright (c) 2021-2026 Timothée David--Cléris <tim.shamrock@proton.me>
5// SPDX-License-Identifier: CeCILL Free Software License Agreement v2.1
6// Shamrock is licensed under the CeCILL 2.1 License, see LICENSE for more information
7//
8// -------------------------------------------------------//
9
10#pragma once
11
19#include "nlohmann/json.hpp"
22
23namespace shammodels::common {
24
25 template<class T>
26 inline py::object to_py_json(const T &self) {
27 auto json_loads = py::module_::import("json").attr("loads");
28 nlohmann::json j = self;
29 return json_loads(j.dump());
30 }
31
32 template<class T>
33 inline T from_py_json(py::object json_data) {
34 auto json_dumps = py::module_::import("json").attr("dumps");
35 std::string j = json_dumps(json_data).cast<std::string>();
36 return nlohmann::json::parse(j).get<T>();
37 }
38
39 template<class TConfig>
40 inline void add_json_defs(py::class_<TConfig> &cls) {
41 cls.def(
42 "to_json",
43 [](TConfig &self) {
44 return shammodels::common::to_py_json(self);
45 },
46 "Converts the config to a json like dictionary");
47
48 cls.def(
49 "from_json",
50 [](TConfig &self, py::object json_data) {
51 self = shammodels::common::from_py_json<TConfig>(json_data);
52 },
53 "Converts a json like dictionary to a config");
54 }
55} // namespace shammodels::common
Pybind11 include and definitions.