1// Copyright Louis Dionne 2013-2022
2// Distributed under the Boost Software License, Version 1.0.
3// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
4
5#include <boost/hana.hpp>
6
7#include <iostream>
8#include <string>
9#include <type_traits>
10#include <utility>
11namespace hana = boost::hana;
12using namespace std::literals;
13
14
15//! [utilities]
16template <typename Xs>
17std::string join(Xs&& xs, std::string sep) {
18 return hana::fold(hana::intersperse(std::forward<Xs>(xs), sep), "", hana::_ + hana::_);
19}
20
21std::string quote(std::string s) { return "\"" + s + "\""; }
22
23template <typename T>
24auto to_json(T const& x) -> decltype(std::to_string(x)) {
25 return std::to_string(x);
26}
27
28std::string to_json(char c) { return quote(s: {c}); }
29std::string to_json(std::string s) { return quote(s); }
30//! [utilities]
31
32//! [Struct]
33template <typename T>
34 std::enable_if_t<hana::Struct<T>::value,
35std::string> to_json(T const& x) {
36 auto json = hana::transform(hana::keys(x), [&](auto name) {
37 auto const& member = hana::at_key(x, name);
38 return quote(hana::to<char const*>(name)) + " : " + to_json(member);
39 });
40
41 return "{" + join(std::move(json), ", ") + "}";
42}
43//! [Struct]
44
45//! [Sequence]
46template <typename Xs>
47 std::enable_if_t<hana::Sequence<Xs>::value,
48std::string> to_json(Xs const& xs) {
49 auto json = hana::transform(xs, [](auto const& x) {
50 return to_json(x);
51 });
52
53 return "[" + join(std::move(json), ", ") + "]";
54}
55//! [Sequence]
56
57
58int main() {
59//! [usage]
60struct Car {
61 BOOST_HANA_DEFINE_STRUCT(Car,
62 (std::string, brand),
63 (std::string, model)
64 );
65};
66
67struct Person {
68 BOOST_HANA_DEFINE_STRUCT(Person,
69 (std::string, name),
70 (std::string, last_name),
71 (int, age)
72 );
73};
74
75Car bmw{.brand: "BMW", .model: "Z3"}, audi{.brand: "Audi", .model: "A4"};
76Person john{.name: "John", .last_name: "Doe", .age: 30};
77
78auto tuple = hana::make_tuple(john, audi, bmw);
79std::cout << to_json(xs: tuple) << std::endl;
80//! [usage]
81}
82

source code of boost/libs/hana/example/tutorial/introspection.json.cpp