LLVM: llvm::json::OStream Class Reference (original) (raw)
json::OStream allows writing well-formed JSON without materializing all structures as json::Value ahead of time. More...
json::OStream allows writing well-formed JSON without materializing all structures as json::Value ahead of time.
It's faster, lower-level, and less safe than OS << json::Value. It also allows emitting more constructs, such as comments.
Only one "top-level" object can be written to a stream. Simplest usage involves passing lambdas (Blocks) to fill in containers:
json::OStream J(OS); J.array([&]{ for (const Event &E : Events) J.object([&] { J.attribute("timestamp", int64_t(E.Time)); J.attributeArray("participants", [&] { for (const Participant &P : E.Participants) J.value(P.toString()); }); }); });
This would produce JSON like:
[ { "timestamp": 19287398741, "participants": [ "King Kong", "Miley Cyrus", "Cleopatra" ] }, ... ]
The lower level begin/end methods (arrayBegin()) are more flexible but care must be taken to pair them correctly:
json::OStream J(OS); for (const Event &E : Events) { J.objectBegin(); J.attribute("timestamp", int64_t(E.Time)); J.attributeBegin("participants"); for (const Participant &P : E.Participants) J.value(P.toString()); J.attributeEnd(); J.objectEnd(); } J.arrayEnd();
If the call sequence isn't valid JSON, asserts will fire in debug mode. This can be mismatched begin()/end() pairs, trying to emit attributes inside an array, and so on. With asserts disabled, this is undefined behavior.