Glaze provides a YAML 1.2 reader and writer. To use YAML support, you must include glaze/yaml.hpp as it is not included in the main glaze/glaze.hpp header. You can reuse the same glz::meta specializations used for JSON.
Use glz::write_yaml to serialize a structure to a string and glz::read_yaml to deserialize a string into a structure. Both functions return an error_ctx which is truthy if an error occurred. Use glz::format_error to convert the error context into a human-readable message.
#include "glaze/yaml.hpp"
struct retry_policy
{
int attempts = 5;
int backoff_ms = 250;
};
template <>
struct glz::meta<retry_policy>
{
using T = retry_policy;
static constexpr auto value = object(&T::attempts, &T::backoff_ms);
};
struct app_config
{
std::string host = "127.0.0.1";
int port = 8080;
retry_policy retry{};
std::vector<std::string> features{"metrics"};
};
template <>
struct glz::meta<app_config>
{
using T = app_config;
static constexpr auto value = object(&T::host, &T::port, &T::retry, &T::features);
};
app_config cfg{};
std::string yaml{};
auto write_error = glz::write_yaml(cfg, yaml);
if (write_error) {
const auto message = glz::format_error(write_error, yaml);
// handle the error message
}
app_config loaded{};
auto read_error = glz::read_yaml(loaded, yaml);
if (read_error) {
const auto message = glz::format_error(read_error, yaml);
// handle the error message
}