Basics¶
The external library used by the JSON Interface is JSON for Modern C++. The basic concepts necessary to understand the following sections are provided here.
Including the library¶
#include "json/src/json.hpp"
Serialisation and deserialisation¶
Parse a JSON-formatted std::string as nlohmann::json (deserialisation):
std::string str = "[0, 1, 2]";
nlohmann::json j = nlohmann::json::parse( str );
Parse a JSON file as nlohmann::json (deserialisation):
std::string filePath = ...
std::ifstream stream( filePath );
nlohmann::json j = nlohmann::json::parse( stream );
Convert a nlohmann::json object to JSON-formatted std::string (serialisation):
nlohmann::json j = ...
std::string oneLineString = j.dump( );
std::string multiLineStringWithIndent = j.dump( 2 );
where the (optional) argument of the dump method is the number of spaces used for each indentation level.
Print a nlohmann::json object as JSON-formatted text (serialisation):
nlohmann::json j = ...
std::cout << j << std::endl;
std::cout << j.dump( 2 ) << std::endl;
Value types¶
A nlohmann::json object can have 6 possible value types. The value type of a nlohmann::json object can be inferred during construction, or later during its lifecycle. The value type of a nlohmann::json object can change.
null
nlohmann::json j; // j.is_null( ) -> true nlohmann::json k = ... // k.is_null( ) -> false k = json( ); // k.is_null( ) -> trueobject: similar to
std::map, but with the possibility to mix different value types and with keys always of type string.nlohmann::json j = { { "a", "zero" }, { "b", 1 } }; // j.is_object( ) -> true j[ "b" ]; // 1 j.size( ); // 2 nlohmann::json k; // k.is_object( ) -> false k[ "a" ] = 0; // k.is_object( ) -> truearray: similar to
std::vector, but with the possibility to mix different value types.nlohmann::json j = { 0, "one" }; // j.is_array( ) -> true j[ 1 ]; // "one" j.empty( ); // false nlohmann::json k; // k.is_array( ) -> false k[ 0 ] = 0.5; // k.is_array( ) -> true k.push_back( "pi" ); // // k[ "b" ] = 1; // run-time error k = json( ); // k.is_null( ) -> true k[ "b" ] = 1; // k.is_object( ) -> truestring: similar to
std::string.number: similar to
double,floatorint.boolean: similar to
bool.
The types object and array are known as structured types (the method is_structured will return true), while the types string, number and boolean are known as primitive types (the method is_primitive will return true).
Structured nlohmann::json objects are containers of nlohmann::json objects (of any value type). This means that if we create the following nlohmann::json object of array type:
double aDouble = 1.0;
std::string aString = "two";
nlohmann::json j = { aDouble, aString };
then when we access any of its elements (e.g. j[ 0 ] or j[ 1 ]) we will not get a double or std::string, but a nlohmann::json object (with value type number or string in this case).