Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emitting JSON with yaml-cpp?

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?

like image 880
Jim Avatar asked May 10 '17 21:05

Jim


2 Answers

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 */;
like image 150
Jesse Beder Avatar answered Nov 19 '22 16:11

Jesse Beder


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.

like image 1
Kerrick Staley Avatar answered Nov 19 '22 17:11

Kerrick Staley