Skip to content

Instantly share code, notes, and snippets.

@univrsal
Created November 21, 2020 20:56
Show Gist options
  • Save univrsal/b06c9f5cef011b6394484452ece0ff9d to your computer and use it in GitHub Desktop.
Save univrsal/b06c9f5cef011b6394484452ece0ff9d to your computer and use it in GitHub Desktop.
Dumb and slow c++ json pretty printer
void indent_json(std::string &json)
{
std::stringstream tmp;
int indent_level = 0;
char prev = 0;
for (auto it = json.begin(); it < json.end(); it++) {
switch (*it) {
case '{':
case '[':
indent_level++;
case ',':
tmp << *it << '\n';
for (int i = 0; i < indent_level; i++)
tmp << " ";
break;
case '}':
case ']':
tmp << '\n';
indent_level--;
for (int i = 0; i < indent_level; i++)
tmp << " ";
tmp << *it;
break;
case '"':
prev = 0;
do {
tmp << *it;
prev = *it++;
} while (*it != '"' || prev == '\\');
tmp << *it;
break;
case ' ':
break;
case ':':
tmp << *it << ' ';
break;
default:
tmp << *it;
}
}
json = tmp.str();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment