3

I am trying to prepare json request using c++. Like this:

string key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

std::string data = "{\n"
"    \"foo\": key\n"
"}";

When I print this, it's shows like :

"foo": key

But I need like this :

"foo": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

So, please someone help me. How to do this? Thanks in advance.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Jayesh
  • 4,755
  • 9
  • 32
  • 62
  • To begin with, and to help you solve your problem, the C++ compiler will not parse the contents of string literals, looking for variables or other expressions. Fortunately you can append to `std::string` objects using the normal `+` operator. Like e.g. `std::string a = "a", b = "b", ab = a + b;` – Some programmer dude Jul 11 '19 at 06:20
  • 2
    To continue, you really shouldn't attempt to create or parse JSON yourself, it's really quite complicated. Find a library to help you with it, there are quite a few C++ and C libraries that you can use. – Some programmer dude Jul 11 '19 at 06:21
  • Possible duplicate of https://stackoverflow.com/questions/37956090/string-interpolation-in-c-construct-a-stdstring-with-embedded-values-e-g – StoryTeller - Unslander Monica Jul 11 '19 at 06:21

4 Answers4

3

C++ doesn't expand variables inside a string constant, so if you have "key" inside such a string, it'll just be interpreted as the string "key" rather than expanded as a variable.

What you want to do is concatenate the contents of the variable "key" with the rest of your string. In C++, you can just do this with the concatenation operator "+".

So you'll want something like:

std::string data = "{\n"
"    \"foo\": " + key + "\n"
"}"
simplicio
  • 200
  • 2
  • 7
2

You can not expect the string key to be replaced with value of variable key. Though some languages support string interpolation but as far as I know c++ does not. You can create the json string by concatenating the string before key, the key, and string after key

std::string data = "{\n \"foo\": " + key + "\n}";
Ashwani
  • 1,938
  • 11
  • 15
1
  std::string key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  std::string data = "{\n"
  "    \"foo\": ";
  data += key;
  data += "\n"
  "}";
alon
  • 220
  • 1
  • 16
1

you can for sure do what others suggested:

std::string data = "{\n\"foo\":" + key + "\n}";

but you can use (and i would advice you) a nice lib called nlohmann::json

and do:

nlohmann::json j;
std::string k{"123-ABC"};
j["foo"] = k;
std::cout << j.dump();
//prints {"foo":"123-ABC"}
std::cout << j.dump(2);
//prints:
//    {
//      "foo": "123-ABC"
//    }
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97