nlohmann::basic_json_view::operator<<¶
std::ostream& operator<<(std::ostream& o, const basic_json_view& v);
Not available when JSON_NO_IO is defined.
Serializes the given view v to the output stream o, using dump -- exactly as operator<<(std::ostream&, const basic_json&) does for a basic_json value.
- The indentation of the output can be controlled with the member variable
widthof the output streamo. For instance, using the manipulatorstd::setw(4)onosets the indentation level to4, and the serialization result is the same as callingv.dump(4). Awidthof0or less (the default) selects the most compact representation, asv.dump(-1)does. - The indentation character can be controlled with the member variable
fillof the output streamo. For instance, the manipulatorstd::setfill('\t')sets indentation to use a tab character rather than the default space character. - As for
basic_json,o'swidthis reset to0after this call, whether or not it was greater than0before.
Numbers are always written as v.dump() writes them by default, i.e. as with number_format::shortest; there is no way to select number_format::source through the stream.
Parameters¶
o(in, out)- stream to write to
v(in)- view to serialize
Return value¶
the stream o
Exceptions¶
May throw std::bad_alloc, propagated from dump. Unlike operator<<(std::ostream&, const basic_json&), there is no UTF-8 decoding step that could throw type_error.316, and no error_handler to choose between -- see the Exceptions of dump.
Complexity¶
Linear, as dump.
Examples¶
Example
The example below writes one record out of a larger batch straight to a log stream -- compact for a one-line entry, and pretty-printed with std::setw/std::setfill for a readable dump -- without ever building a BasicJsonType value for the record, or for the rest of the batch.
#include <iostream>
#include <iomanip>
#include <nlohmann/json_view.hpp>
using json_document = nlohmann::json_document;
using json_view = nlohmann::json_view;
int main()
{
// one order out of a large incoming batch -- write it straight to a log
// stream without ever building a basic_json value for it, or for the
// rest of the batch
const json_document doc = json_document::parse(R"(
[{"id": 1, "item": "cable"}, {"id": 2, "item": "adapter"}]
)");
const json_view orders = doc.root();
// compact, for a one-line log entry
std::cout << orders[1] << '\n';
// std::setw sets the indentation level, exactly as for basic_json
std::cout << std::setw(2) << orders[1] << "\n\n";
// std::setfill changes the indentation character
std::cout << std::setw(1) << std::setfill('\t') << orders[1] << '\n';
}
Output:
{"id":2,"item":"adapter"}
{
"id": 2,
"item": "adapter"
}
{
"id": 2,
"item": "adapter"
}
See also¶
- dump - serialize to a JSON-formatted string
operator<<(std::ostream&)- the corresponding operator forbasic_jsonJSON_NO_IO- switch off functions relying on certain C++ I/O headers
Version history¶
- Added in version 3.13.0 unreleased.