使用 yaml-cpp 发出 JSON?

问题描述 投票:0回答:3

我在项目中使用 yaml-cpp 来处理各种事情。 现在我想以 JSON 形式写出一些数据。 由于 JSON 是 YAML 的子集,至少对于我需要的功能来说,我知道应该可以在 yaml-cpp 中设置一些选项来输出纯 JSON。 这是怎么做到的?

json yaml yaml-cpp
3个回答
5
投票

yaml-cpp 没有直接强制 JSON 兼容输出的方法,但您可以模拟它。

YAML:Emitter Emitter;
emitter << YAML:: DoubleQuoted << YAML::Flow << /* rest of code */;

2
投票

Jesse Beder的回答似乎对我不起作用;我仍然使用 YAML 语法得到多行输出。然而,我发现通过在

<< YAML::BeginSeq
之后立即添加
<< YAML::Flow
,您可以强制所有内容都以 JSON 语法结束在一行上。然后,您必须删除开头的
[
字符:

YAML::Emitter emitter;
emitter << YAML::DoubleQuoted << YAML::Flow << YAML::BeginSeq << node;
std::string json(emitter.c_str() + 1);  // Remove beginning [ character

这是一个完整的示例

不过,仍然存在一个主要问题:数字被引用,将它们转换为字符串。我不确定这是否是

YAML::DoubleQuoted
的故意行为;查看测试,我没有看到任何测试用例涵盖将
DoubleQuoted
应用于数字时会发生什么。此问题已提交此处


0
投票

所有上述答案都没有为重要的 yaml 文件生成正确的 json。

如果您不介意添加(或已经添加)

nlohmann::json
,那么, mircodz 的以下代码片段从 yaml 节点生成有效的 json。

// Author: mircodz (Mirco De Zorzi)
// URL: https://github.com/mircodz/tojson/blob/master/tojson.hpp

inline nlohmann::json parse_scalar(const YAML::Node &node) {
  int i;
  double d;
  bool b;
  std::string s;

  if (YAML::convert<int>::decode(node, i))
    return i;
  if (YAML::convert<double>::decode(node, d))
    return d;
  if (YAML::convert<bool>::decode(node, b))
    return b;
  if (YAML::convert<std::string>::decode(node, s))
    return s;

  return nullptr;
}

inline nlohmann::json yaml2json(const YAML::Node &root) {
  nlohmann::json j{};

  switch (root.Type()) {
  case YAML::NodeType::Null:
    break;
  case YAML::NodeType::Scalar:
    return parse_scalar(root);
  case YAML::NodeType::Sequence:
    for (auto &&node : root)
      j.emplace_back(yaml2json(node));
    break;
  case YAML::NodeType::Map:
    for (auto &&it : root)
      j[it.first.as<std::string>()] = yaml2json(it.second);
    break;
  default:
    break;
  }
  return j;
}
© www.soinside.com 2019 - 2024. All rights reserved.