Reputation: 265
I'm working with an API in C++ that uses raw JSON strings. For example:
string data = R"JSON({
"key1": "value1",
"key2": "value2"
})JSON";
I would like to be use variables as the values. For example:
string value1 = "55.2";
string value2 = "3.14";
string data = R"JSON({
"key1": value1, //somehow use the string variables here
"key2": value2
})JSON";
Is anything like this possible?
Upvotes: 1
Views: 1852
Reputation: 3608
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.
Upvotes: 2
Reputation: 12928
You can concatenate strings by using operator+
.
#include <iostream>
#include <string>
int main() {
std::string value = "55.2";
std::string str = R"({"key1":)" + value + "}";
std::cout << str;
}
Upvotes: 3