mirror of
https://github.com/nlohmann/json.git
synced 2026-02-24 12:26:25 +00:00
Add ignore_trailing_commas option (#4609)
Added examples and modified the corresponding documents and unit tests. Signed-off-by: chirsz-ever <chirsz-ever@outlook.com> Co-authored-by: Niels Lohmann <niels.lohmann@gmail.com>
This commit is contained in:
@@ -206,6 +206,7 @@ class SaxCountdown : public nlohmann::json::json_sax_t
|
||||
json parser_helper(const std::string& s);
|
||||
bool accept_helper(const std::string& s);
|
||||
void comments_helper(const std::string& s);
|
||||
void trailing_comma_helper(const std::string& s);
|
||||
|
||||
json parser_helper(const std::string& s)
|
||||
{
|
||||
@@ -225,6 +226,8 @@ json parser_helper(const std::string& s)
|
||||
|
||||
comments_helper(s);
|
||||
|
||||
trailing_comma_helper(s);
|
||||
|
||||
return j;
|
||||
}
|
||||
|
||||
@@ -259,10 +262,11 @@ bool accept_helper(const std::string& s)
|
||||
// 6. check if this approach came to the same result
|
||||
CHECK(ok_noexcept == ok_noexcept_cb);
|
||||
|
||||
// 7. check if comments are properly ignored
|
||||
// 7. check if comments or trailing commas are properly ignored
|
||||
if (ok_accept)
|
||||
{
|
||||
comments_helper(s);
|
||||
trailing_comma_helper(s);
|
||||
}
|
||||
|
||||
// 8. return result
|
||||
@@ -302,6 +306,38 @@ void comments_helper(const std::string& s)
|
||||
}
|
||||
}
|
||||
|
||||
void trailing_comma_helper(const std::string& s)
|
||||
{
|
||||
json _;
|
||||
|
||||
// parse/accept with default parser
|
||||
CHECK_NOTHROW(_ = json::parse(s));
|
||||
CHECK(json::accept(s));
|
||||
|
||||
// parse/accept while allowing trailing commas
|
||||
CHECK_NOTHROW(_ = json::parse(s, nullptr, false, false, true));
|
||||
CHECK(json::accept(s, false, true));
|
||||
|
||||
// note: [,] and {,} are not allowed
|
||||
if (s.size() > 1 && (s.back() == ']' || s.back() == '}') && !_.empty())
|
||||
{
|
||||
std::vector<std::string> json_with_trailing_commas;
|
||||
json_with_trailing_commas.push_back(s.substr(0, s.size() - 1) + " ," + s.back());
|
||||
json_with_trailing_commas.push_back(s.substr(0, s.size() - 1) + "," + s.back());
|
||||
json_with_trailing_commas.push_back(s.substr(0, s.size() - 1) + ", " + s.back());
|
||||
|
||||
for (const auto& json_with_trailing_comma : json_with_trailing_commas)
|
||||
{
|
||||
CAPTURE(json_with_trailing_comma)
|
||||
CHECK_THROWS_AS(_ = json::parse(json_with_trailing_comma), json::parse_error);
|
||||
CHECK(!json::accept(json_with_trailing_comma));
|
||||
|
||||
CHECK_NOTHROW(_ = json::parse(json_with_trailing_comma, nullptr, true, false, true));
|
||||
CHECK(json::accept(json_with_trailing_comma, false, true));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("parser class")
|
||||
|
||||
Reference in New Issue
Block a user