diff --git a/include/nlohmann/detail/output/fancy_serializer.hpp b/include/nlohmann/detail/output/fancy_serializer.hpp index c210992b9..ee6a71d28 100644 --- a/include/nlohmann/detail/output/fancy_serializer.hpp +++ b/include/nlohmann/detail/output/fancy_serializer.hpp @@ -35,12 +35,13 @@ struct fancy_serializer_style unsigned int strings_maximum_length = 0; bool space_after_colon = false; + bool space_after_comma = false; bool multiline = false; void set_old_multiline() { - space_after_colon = multiline = true; + space_after_colon = space_after_comma = multiline = true; } }; @@ -298,6 +299,12 @@ class fancy_serializer } const int newline_len = (active_style->multiline ? 1 : 0); + using pair = std::pair; + auto comma_string = + active_style->multiline ? pair(",\n", 2) : + active_style->space_after_comma ? pair(", ", 2) : + pair(",", 1); + o->write_characters("[\n", 1 + newline_len); // first n-1 elements @@ -306,7 +313,7 @@ class fancy_serializer { o->write_characters(indent_string.c_str(), new_indent); dump(*i, ensure_ascii, depth + 1, active_style); - o->write_characters(",\n", 1 + newline_len); + o->write_characters(comma_string.first, comma_string.second); } // last element diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index 5b78a676e..c1ede78ab 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -10105,12 +10105,13 @@ struct fancy_serializer_style unsigned int strings_maximum_length = 0; bool space_after_colon = false; + bool space_after_comma = false; bool multiline = false; void set_old_multiline() { - space_after_colon = multiline = true; + space_after_colon = space_after_comma = multiline = true; } }; @@ -10368,6 +10369,12 @@ class fancy_serializer } const int newline_len = (active_style->multiline ? 1 : 0); + using pair = std::pair; + auto comma_string = + active_style->multiline ? pair(",\n", 2) : + active_style->space_after_comma ? pair(", ", 2) : + pair(",", 1); + o->write_characters("[\n", 1 + newline_len); // first n-1 elements @@ -10376,7 +10383,7 @@ class fancy_serializer { o->write_characters(indent_string.c_str(), new_indent); dump(*i, ensure_ascii, depth + 1, active_style); - o->write_characters(",\n", 1 + newline_len); + o->write_characters(comma_string.first, comma_string.second); } // last element diff --git a/test/src/unit-fancy-serialization.cpp b/test/src/unit-fancy-serialization.cpp index 9c13177a3..9e350678d 100644 --- a/test/src/unit-fancy-serialization.cpp +++ b/test/src/unit-fancy-serialization.cpp @@ -280,6 +280,14 @@ TEST_CASE("serialization") SECTION("Spaces after commas are controllable separately from multiline") { + SECTION("commas") + { + fancy_serializer_style style; + style.space_after_comma = true; + auto str = fancy_to_string({1, 2, 3}, style); + CHECK(str == "[1, 2, 3]"); + } + SECTION("colons") { fancy_serializer_style style;