nlohmann::operator<<(basic_json), nlohmann::operator<<(json_pointer)¶
std::ostream&operator<<(std::ostream&o,constbasic_json&j);// (1)
std::ostream&operator<<(std::ostream&o,constjson_pointer&ptr);// (2)
- Serialize the given JSON value
jto the output streamo. The JSON value will be serialized using thedumpmember function.- 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 to4and the serialization result is the same as callingdump(4). - 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.
- The indentation of the output can be controlled with the member variable
- Write a string representation of the given JSON pointer
ptrto the output streamo. The string representation is obtained using theto_stringmember function.
Parameters¶
o(in, out)- stream to write to
j(in)- JSON value to serialize
ptr(in)- JSON pointer to write
Return value¶
the stream o
Exceptions¶
- Throws
type_error.316if a string stored inside the JSON value is not UTF-8 encoded. Note that unlike thedumpmember functions, noerror_handlercan be set. - None.
Complexity¶
Linear.
Notes¶
Deprecation
Function std::ostream&operator<<(std::ostream&o,constbasic_json&j) replaces function std::ostream&operator>>(constbasic_json&j,std::ostream&o) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j>>o; with o<<j;.
Examples¶
Example: (1) serialize JSON value to stream
The example below shows the serialization with different parameters to width to adjust the indentation level.
#include<iostream>
#include<iomanip>
#include<nlohmann/json.hpp>
usingjson=nlohmann::json;
intmain()
{
// create JSON values
jsonj_object={{"one",1},{"two",2}};
jsonj_array={1,2,4,8,16};
// serialize without indentation
std::cout<<j_object<<"\n\n";
std::cout<<j_array<<"\n\n";
// serialize with indentation
std::cout<<std::setw(4)<<j_object<<"\n\n";
std::cout<<std::setw(2)<<j_array<<"\n\n";
std::cout<<std::setw(1)<<std::setfill('\t')<<j_object<<"\n\n";
}
Output:
{"one":1,"two":2}
[1,2,4,8,16]
{
"one":1,
"two":2
}
[
1,
2,
4,
8,
16
]
{
"one":1,
"two":2
}
Example: (2) write JSON pointer to stream
The example below shows how to write a JSON pointer to a stream.
#include<iostream>
#include<nlohmann/json.hpp>
usingjson=nlohmann::json;
intmain()
{
// create JSON pointer
json::json_pointerptr("/foo/bar/baz");
// write string representation to stream
std::cout<<ptr<<std::endl;
}
Output:
/foo/bar/baz
Version history¶
- Added in version 1.0.0. Added support for indentation character and deprecated
std::ostream&operator>>(constbasic_json&j,std::ostream&o)in version 3.0.0. - Added in version 3.11.0.