Many JSON parsers support the option to comment out fields. Is it possible to request such a feature in the nlohmann parser too?
For this library, we do not plan to support any input which is not compliant to RFC 7159.
See #376, #363, #311, #294, #192.
@nlohmann
Thanks.
@kinchungwong
It's been a long time, and I think we can consider replanning the introduction of json comments
Not support for JSON comments is a very sad thing, as is the ability to debug data, indicate what values are available, and so on.If you need to enforce the JSON standard, consider adding a separate interface for parsing JSON strings with JSON comments
Such as:
string s = "{/**///\n}";
s = nlohmann::json::remove_comments (s);
auto o = nlohmann::json::parse (s);
But removing comments is not possible by just a regular expression. It would mean integration into the lexer.
So can reopen the question?
No, because this library will not support comments. If anyone wants to provide a pull request with a compact comment stripper, I will have a look.
I think can add this code to the project:
#ifndef __JSON_PREPROCESS_HPP__
#define __JSON_PREPROCESS_HPP__
#include <string>
class JsonPreprocess {
enum class CurrentState {
Normal, Quote, QuoteIgnore, BeginComment, CommentLine, CommentBlock, CommentBlockEnd,
};
public:
static std::string remove_comments (std::string _data) {
std::string _ret = "";
auto _state = CurrentState::Normal;
for (char ch : _data) {
if (_state == CurrentState::Normal) {
if (ch == '"') {
_ret += ch;
_state = CurrentState::Quote;
} else if (ch == '/') {
_state = CurrentState::BeginComment;
} else {
_ret += ch;
}
} else if (_state == CurrentState::Quote) {
if (ch == '"') {
_ret += ch;
_state = CurrentState::Normal;
} else if (ch == '\\') {
_ret += ch;
_state = CurrentState::QuoteIgnore;
} else {
_ret += ch;
}
} else if (_state == CurrentState::QuoteIgnore) {
_ret += ch;
_state = CurrentState::Quote;
} else if (_state == CurrentState::BeginComment) {
_state = (ch == '/' ? CurrentState::CommentLine : CurrentState::CommentBlock);
} else if (_state == CurrentState::CommentLine) {
if (ch == '\r' || ch == '\n') {
_ret += ch;
_state = CurrentState::Normal;
} else {
_state = CurrentState::CommentLine;
}
} else if (_state == CurrentState::CommentBlock) {
_state = (ch == '*' ? CurrentState::CommentBlockEnd : CurrentState::CommentBlock);
} else if (_state == CurrentState::CommentBlockEnd) {
_state = (ch == '*' ? CurrentState::CommentBlockEnd : (ch == '/' ? CurrentState::Normal : CurrentState::CommentBlock));
}
}
return _ret;
}
};
#endif //__JSON_PREPROCESS_HPP__
I'm currently working on extending the parser and will open a PR later this week.