Skip to content

Commit aa4c45e

Browse files
committed
Added to_string (with ugly macro) and tests
1 parent ee4028b commit aa4c45e

3 files changed

Lines changed: 45 additions & 0 deletions

File tree

include/nlohmann/json.hpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7965,6 +7965,21 @@ class basic_json
79657965

79667966
/// @}
79677967
};
7968+
7969+
/*!
7970+
@brief user-defined to_string function for JSON values
7971+
7972+
This function implements a user-defined to_string for JSON objects.
7973+
7974+
@param[in] j a JSON object
7975+
@return a std::string object
7976+
*/
7977+
7978+
NLOHMANN_BASIC_JSON_TPL_DECLARATION
7979+
std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
7980+
{
7981+
return j.dump();
7982+
}
79687983
} // namespace nlohmann
79697984

79707985
///////////////////////

single_include/nlohmann/json.hpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20766,6 +20766,21 @@ class basic_json
2076620766

2076720767
/// @}
2076820768
};
20769+
20770+
/*!
20771+
@brief user-defined to_string function for JSON values
20772+
20773+
This function implements a user-defined to_string for JSON objects.
20774+
20775+
@param[in] j a JSON object
20776+
@return a std::string object
20777+
*/
20778+
20779+
NLOHMANN_BASIC_JSON_TPL_DECLARATION
20780+
std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
20781+
{
20782+
return j.dump();
20783+
}
2076920784
} // namespace nlohmann
2077020785

2077120786
///////////////////////

test/src/unit-serialization.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,4 +173,19 @@ TEST_CASE("serialization")
173173
test("\xE1\x80\xE2\xF0\x91\x92\xF1\xBF\x41", "\\ufffd" "\\ufffd" "\\ufffd" "\\ufffd" "\x41");
174174
}
175175
}
176+
177+
SECTION("to_string")
178+
{
179+
auto test = [&](std::string const & input, std::string const & expected)
180+
{
181+
using std::to_string;
182+
json j = input;
183+
CHECK(to_string(j) == "\"" + expected + "\"");
184+
};
185+
186+
test("{\"x\":5,\"y\":6}", "{\\\"x\\\":5,\\\"y\\\":6}");
187+
test("{\"x\":[10,null,null,null]}", "{\\\"x\\\":[10,null,null,null]}");
188+
test("test", "test");
189+
test("[3,\"false\",false]", "[3,\\\"false\\\",false]");
190+
}
176191
}

0 commit comments

Comments
 (0)