Using boost::json::serializer
as shown in the example in docs - quick look saves the json-tree in compact format.
Is there a way to instruct the serializer
to output a human readable file (i.e. with newlines and whitespaces)? I searched around, but didn't find any hints.
NB: Even better would be writing the higher levels of the tree readably, and some objects, or arrays (maybe marked ones) in compact format.
The shortened example code could look like this:
#include <iostream>
#include <boost/json.hpp>
#include <boost/json/src.hpp> // use header-only
using namespace boost;
int main(int /*argc*/, char */*argv*/[]) {
json::value jv = {
{ "pi", 3.141 },
{"list", {1, 0, 2}},
};
json::serializer sr;
sr.reset( &jv );
do {
char buf[ 16 ];
std::cout << sr.read( buf );
} while( ! sr.done() );
}
This (correctly) outputs {"pi":3.141E0,"list":[1,0,2]}
, but I'd rather have:
{
"pi":3.141E0,
"list":
[
1,
0,
2
]
}
or (the "NB"-version):
{
"pi":3.141E0,
"list":[1,0,2]
}
Is this possible with boost::json
without writing it myself?
This is not a feature of the library. The library has goals stated in the intro. It doesn't include user-friendly presentation formatting. In fact, even their number formatting can be said to be down-right user hostile.
The promise of the library centers at data interchange between computer systems:
This library focuses on a common and popular use-case: parsing and serializing to and from a container called value which holds JSON types. Any value which you build can be serialized and then deserialized, guaranteeing that the result will be equal to the original value. Whatever JSON output you produce with this library will be readable by most common JSON implementations in any language.
There's an example that shows how to do simple pretty printing if you want to avoid a large part of the work/have a reasonable starting point to not forget too many things: https://www.boost.org/doc/libs/1_76_0/libs/json/doc/html/json/examples.html
Alternatively, you can use any of the existing JSON libraries with a richer feature set. Keep in mind they will make different trade-offs, so you may run into other limitations.