If you just need to do it once, you can follow the suggestion from the other answers/comments and concatenate the resulting string manually.
If you might need to do something more than that (e.g. build the huge JSON request for some network API, or parse the huge response back), keep reading :)
I strongly dislike the idea of concatenating JSON manually using string operator+
, string streams, sprintf
, or any other string operations.
Any solution based on string concatenation might work when you work with numbers only and when your JSON is small, but if you ever need to concatenate string values into JSON, you get in trouble as soon as you have a "
or a \
character in your string. You'll need to do proper escaping. Also, if the JSON object you concatenate grows large, maintaining that code would be a nightmare.
Solutions?
If you need to use C++, find a library that does JSON operations for you. There are plenty. It's often better to use the tested third-party code that solves this particular task well. Yes, it might take more time to start using an external dependency than concatenating the string manually, but it just makes the code better.
If your task is heavily related to calling network APIs and manipulating JSONs, C++ might not be the best language of choice for that, unless there are other considerations (or unless it's a programming assignment :) ). Modern scripting languages (Python, JavaScript, moth others) support JSON and network calls natively.