You question isn't very clear if I have to be honest, but I am almost sure this is a classic example of an XY problem.
IMHO, the main mistake is is that you are trying to format JSON by hand, which is by experience quite tricky and error prone.
Unless you are actually operating on a very small and strict set of inputs, there's an almost 100% certainty you will generate malformed JSON outputs in some cases. For instance, you have to also remember that all strings should be valid UTF-8, which means you have to either check your inputs or escape any weird character they might contain. You also have to escape anything that is not valid in a JSON string, such as "
, like specified by the JSON standard.
This is why I think generating JSON by hand should only be done as a solution of last resort, i.e. if you have an embedded device and you can't afford to use any kind of library due to extremely severe memory constraints.
One library I often recommend is nlohmann/json, which might not be the fastest around1 but it is definitely one of the easiest to use. This is mostly due to it being header-only library and the fact that nlohmann::json
is compatible with STL algorithms and iterators (it basically behaves like a std::map or vector).
You can then do very neat things, such as:
#include <iostream>
#include <string_view>
#include <unordered_set>
#include <nlohmann/json.hpp>
int main() {
const std::unordered_set<std::string_view> s { "a", "b", "c" };
nlohmann::json jarr {};
for (const auto sv : s) {
jarr.push_back(sv);
}
nlohmann::json jv { { "values", std::move(jarr) } };
std::cout << jv.dump() << '\n';
return 0;
}
This prints {"values":["c","b","a"]}
.
You can even straight out serialize and deserialize arbitrary types (even user defined ones) as a JSON:
#include <iostream>
#include <string_view>
#include <unordered_set>
#include <nlohmann/json.hpp>
int main() {
const std::unordered_set<std::string_view> s { "a", "b", "c" };
nlohmann::json jv { { "values", s } };
std::cout << jv.dump() << '\n';
return 0;
}
1: In my experience, unless you must parse MILLIONS of JSONs per second, most performance considerations become moot. I've seen nlohmann's JSON library in use on the ESP32 and even there it was fast enough for light to moderate JSON parsing and generation.