7

I'm using yaml-cpp on a for a variety of things on my project. Now I want to write out some data as JSON. Since JSON is a subset of YAML, at least for the features I need, I understand it should be possible to set some options in yaml-cpp to output pure JSON. How is that done?

Jim
  • 651
  • 2
  • 7
  • 15

2 Answers2

4

yaml-cpp doesn't directly have a way to force JSON-compatible output, but you can probably emulate it.

YAML:Emitter Emitter;
emitter << YAML:: DoubleQuoted << YAML::Flow << /* rest of code */;
Jesse Beder
  • 33,081
  • 21
  • 109
  • 146
  • That seems to work for my case, valid JSON is emitted. I just have one follow on question: The above results all the JSON being on one long line. Is there a way to also have it have newlines and indentation? – Jim May 12 '17 at 18:35
  • I don't think so. – Jesse Beder May 13 '17 at 20:02
  • This does not seem to work anymore, or at least on more complex YAML. I get everything on different rows with YAML style arrays and objects when doing a complex << node output. – David Jan 17 '18 at 21:53
  • Looks like this might be set on a per node basis? (flow vs no flow) – David Jan 17 '18 at 21:57
  • 1
    this does not work if you have null value. yaml-cpp seems only use ~ as null, I cannot find a way to actually force it use `null` – Wang Jun 05 '20 at 21:07
1

Jesse Beder's answer didn't seem to work for me; I still got multiple lines of output with YAML syntax. However, I found that by adding << YAML::BeginSeq immediately after << YAML::Flow, you can force everything to end up on one line with JSON syntax. You then have to remove the beginning [ character:

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

Here is a fully worked example.

There's still a major issue, though: numbers are quoted, turning them into strings. I'm not sure whether this is an intentional behavior of YAML::DoubleQuoted; looking at the tests, I didn't see any test case that covers what happens when you apply DoubleQuoted to a number. This issue has been filed here.

Kerrick Staley
  • 1,583
  • 2
  • 20
  • 28