add bool to detect comments as run-time option.

mutable-v2
Antonio Cervone 2015-11-30 12:27:35 +01:00
parent de098c4d52
commit 882feb56ac
3 changed files with 23 additions and 17 deletions

View File

@ -338,6 +338,7 @@ struct JsonParser {
size_t i;
string &err;
bool failed;
bool detect_comments;
/* fail(msg, err_ret = Json())
*
@ -397,10 +398,10 @@ struct JsonParser {
*/
void consume_garbage() {
consume_whitespace();
#ifdef JSON11_COMMENTS
if(detect_comments) {
consume_comment();
consume_whitespace();
#endif
}
}
/* get_next_token()
@ -696,8 +697,8 @@ struct JsonParser {
}
};
Json Json::parse(const string &in, string &err) {
JsonParser parser { in, 0, err, false };
Json Json::parse(const string &in, string &err, bool detect_comments) {
JsonParser parser { in, 0, err, false, detect_comments };
Json result = parser.parse_json(0);
// Check for any trailing garbage
@ -709,8 +710,10 @@ Json Json::parse(const string &in, string &err) {
}
// Documented in json11.hpp
vector<Json> Json::parse_multi(const string &in, string &err) {
JsonParser parser { in, 0, err, false };
vector<Json> Json::parse_multi(const string &in,
string &err,
bool detect_comments) {
JsonParser parser { in, 0, err, false, detect_comments };
vector<Json> json_vec;
while (parser.i != in.size() && !parser.failed) {

View File

@ -56,8 +56,6 @@
#include <memory>
#include <initializer_list>
#define JSON11_COMMENTS 1
namespace json11 {
class JsonValue;
@ -147,17 +145,23 @@ public:
}
// Parse. If parse fails, return Json() and assign an error message to err.
static Json parse(const std::string & in, std::string & err);
static Json parse(const char * in, std::string & err) {
static Json parse(const std::string & in,
std::string & err,
bool detect_comments = false);
static Json parse(const char * in,
std::string & err,
bool detect_comments = false) {
if (in) {
return parse(std::string(in), err);
return parse(std::string(in), err, detect_comments);
} else {
err = "null input";
return nullptr;
}
}
// Parse multiple objects, concatenated or separated by whitespace
static std::vector<Json> parse_multi(const std::string & in, std::string & err);
static std::vector<Json> parse_multi(const std::string & in,
std::string & err,
bool detect_comments = false);
bool operator== (const Json &rhs) const;
bool operator< (const Json &rhs) const;

View File

@ -58,7 +58,6 @@ int main(int argc, char **argv) {
std::cout << " - " << k.dump() << "\n";
}
#ifdef JSON11_COMMENTS
const string comment_test = R"({
// comment
"a": 1,
@ -72,13 +71,13 @@ int main(int argc, char **argv) {
})";
string err_comment;
auto json_comment = Json::parse(comment_test, err_comment);
auto json_comment = Json::parse(
comment_test, err_comment, /*detect_comments=*/ true);
if (!err_comment.empty()) {
printf("Failed: %s\n", err_comment.c_str());
} else {
printf("Result: %s\n", json_comment.dump().c_str());
}
#endif
std::list<int> l1 { 1, 2, 3 };
std::vector<int> l2 { 1, 2, 3 };