39 const std::string& json_string,
40 bool with_whitespace =
false,
41 bool preserve_newlines =
true) {
42 if (json_string.empty()) {
46 enum CommentType { NO_COMMENT, SINGLE_COMMENT, MULTI_COMMENT };
47 CommentType inside_comment = CommentType::NO_COMMENT;
48 bool inside_string =
false;
50 std::size_t offset = 0;
51 const std::size_t json_string_size = json_string.size();
52 const std::size_t json_max_index = json_string_size - 1;
54 result.reserve(json_string_size);
56 for (std::size_t i = 0; i < json_string_size; ++i) {
57 const char current_character = json_string[i];
58 const char next_character = i < json_max_index ? json_string[i + 1] : 0;
60 if (inside_comment == CommentType::NO_COMMENT && current_character ==
'"') {
62 inside_string = !inside_string;
66 if (inside_string)
continue;
68 switch (inside_comment) {
69 case CommentType::NO_COMMENT:
70 if (current_character ==
'#' || (current_character ==
'/' && next_character ==
'/')) {
71 inside_comment = SINGLE_COMMENT;
72 result.append(json_string, offset, i - offset);
74 i += (next_character ==
'/') ? 2 : 1;
77 if (current_character ==
'/' && next_character ==
'*') {
78 inside_comment = MULTI_COMMENT;
79 result.append(json_string, offset, i - offset);
85 case CommentType::SINGLE_COMMENT:
86 if ((current_character ==
'\r' && next_character ==
'\n') || current_character ==
'\n') {
87 inside_comment = NO_COMMENT;
88 if (with_whitespace) {
89 result.append(std::string(i - offset,
' '));
90 if (current_character ==
'\r') {
97 if (current_character ==
'\r') {
105 case CommentType::MULTI_COMMENT:
106 if (current_character ==
'*' && next_character ==
'/') {
107 inside_comment = CommentType::NO_COMMENT;
109 if (with_whitespace) {
110 if (preserve_newlines) {
111 std::string temp = json_string.substr(offset, i - offset + 1);
112 std::replace_if(temp.begin(), temp.end(), [](
char ch) {
113 return ch !=
'\n' && ch !=
'\r';
117 result.append(std::string(i - offset + 1,
' '));
129 switch (inside_comment) {
130 case CommentType::NO_COMMENT:
131 result += json_string.substr(offset);
133 case CommentType::SINGLE_COMMENT:
134 if (with_whitespace) {
135 result.append(std::string(json_string_size - offset,
' '));
138 case CommentType::MULTI_COMMENT:
139 if (with_whitespace) {
140 if (preserve_newlines) {
141 std::string temp = json_string.substr(offset, json_string_size - offset);
142 std::replace_if(temp.begin(), temp.end(), [](
char ch) {
143 return ch !=
'\n' && ch !=
'\r';
147 result.append(std::string(json_string_size - offset,
' '));