I have a string which contains JSON-like object flattened (stringify()ed).
I need to JSON-ify it back. It's a custom format, so I wrote function to JSON-ify the string:
#include <string>
#include <unordered_set>
#include <iostream>
const std::unordered_set<std::string> reservedWords{ "coords", "comment" };
std::string jsonify(const std::string &tclString)
{
std::string result;
int level = 0;
const int tabWidth = 4;
bool reservedWord = false;
const auto length = tclString.length();
std::string prevWord;
for (auto idx = 0; idx < length; ++idx)
{
auto ch = tclString[idx];
if (ch == ' ')
result += ' ';
else if (ch == '{')
{
std::string word;
while (++idx < length)
{
ch = tclString[idx];
if (ch == ' ' || ch == '}')
break;
word += ch;
}
result += '{';
if (word == "}")
{
if (reservedWord)
reservedWord = false;
}
else if (!reservedWord)
{
++level;
result += '\n';
result += std::string(level * tabWidth, ' ');
reservedWord = reservedWords.contains(word);
}
--idx;
result += word;
}
else if (ch == '}')
{
if (reservedWord)
{
result += '}';
reservedWord = false;
}
else
{
--level;
result += '\n';
result += std::string(level * tabWidth, ' ');
result += '}';
result += '\n';
}
}
else
{
std::string word;
while (idx < length)
{
if (ch == '}' || ch == ' ' || ch == '{')
break;
word += ch;
++idx;
ch = tclString[idx];
}
--idx;
result += word;
if (!reservedWord)
reservedWord = reservedWords.contains(word);
}
}
return result;
}
int main()
{
std::cout << jsonify("{data {a {obj {coords {10 10} comment {} radius 260 type circle}}}}") << '\n';
std::cout << jsonify("{data {b {obj {coords {-95 -85 -70 -85 -75 -95} comment {abc} type polygon}}}}") << '\n';
std::cout << jsonify("{data {c {obj {coords {-55 -65 -70 -65 -25 -64} comment {abc def} type polygon}}}}") << '\n';
}
Please review the code and let me know how I can make it better?
Thanks in advance.