From 57106a345960d31c4f6df74912c1f0b7e2fa95b5 Mon Sep 17 00:00:00 2001 From: Jiaming Yuan Date: Wed, 18 Sep 2019 03:31:46 -0400 Subject: [PATCH] Fix parsing empty json object. (#4868) * Fix parsing empty json object. * Better error message. --- src/common/json.cc | 17 +++++++++++++++-- tests/cpp/common/test_json.cc | 14 ++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/common/json.cc b/src/common/json.cc index 396140a06..5c14db47b 100644 --- a/src/common/json.cc +++ b/src/common/json.cc @@ -384,8 +384,18 @@ void JsonReader::Error(std::string msg) const { auto end = cursor_.Pos() + kExtend >= raw_str_.size() ? raw_str_.size() : cursor_.Pos() + kExtend; + std::string const& raw_portion = raw_str_.substr(beg, end - beg); + std::string portion; + for (auto c : raw_portion) { + if (c == '\n') { + portion += "\\n"; + } else { + portion += c; + } + } + msg += " "; - msg += raw_str_.substr(beg, end - beg); + msg += portion; msg += '\n'; msg += " "; @@ -488,9 +498,12 @@ Json JsonReader::ParseArray() { } Json JsonReader::ParseObject() { - char ch = GetChar('{'); + GetChar('{'); std::map data; + SkipSpaces(); + char ch = PeekNextChar(); + if (ch == '}') return Json(std::move(data)); while (true) { diff --git a/tests/cpp/common/test_json.cc b/tests/cpp/common/test_json.cc index 1ae31236b..94e87bcac 100644 --- a/tests/cpp/common/test_json.cc +++ b/tests/cpp/common/test_json.cc @@ -214,6 +214,20 @@ TEST(Json, Null) { ASSERT_TRUE(IsA(json["key"])); } +TEST(Json, EmptyObject) { + std::string str = R"json( +{ + "rank": 1, + "statistic": { + + } +} +)json"; + std::stringstream iss(str); + auto json = Json::Load(StringView{str.c_str(), str.size()}); + ASSERT_TRUE(IsA(json["statistic"])); +} + TEST(Json, EmptyArray) { std::string str = R"json( {