1

newbie to c++,

Currently, I have a hard coded json stored in a char array

static CHAR data[]= "{\"id\":1, \"name\":\"test\"}";

I want to make the values in the json coming from dynamic values

for instance

int id = 1;

std::wstring name = "joe";

May I ask how can I achieve that,thanks

epiphany
  • 756
  • 1
  • 11
  • 29
  • 1
    I'd use a JSON library to create and manipulate JSON values. The nlohmann one is really easy to use. Not sure how well it supports wide strings, though; you might have to convert to utf-8 yourself first. – Shawn Apr 02 '19 at 09:47
  • I'm using c++98, nlohmann only support c++11 – epiphany Apr 02 '19 at 09:48
  • @epiphany have you considered rapidjson? – FloIsAwsm Apr 02 '19 at 09:51
  • I am thinking of something like creating a string with both the concat values and then cast it to a char array, can I do that? – epiphany Apr 02 '19 at 09:53
  • Unless you're working on a legacy code base, there's no good reason not to target at least C++11 these days. – Shawn Apr 02 '19 at 09:54
  • unfortunately I am – epiphany Apr 02 '19 at 09:55
  • So something like this? int id = 10; std::string name = "joe"; std::string json = "{\"id\":" + std::to_string(id) + ", \"name\":\"" + name + "\"}";´ – FloIsAwsm Apr 02 '19 at 09:58
  • Yes, but I am having problem at how to convert the string to a char array – epiphany Apr 02 '19 at 10:03
  • you can get inspiration from this link : https://stackoverflow.com/questions/31121378/json-cpp-how-to-initialize-from-string-and-get-string-value you can find also a direct link and sample here http://jsoncpp.sourceforge.net/old.html – ROCFER Apr 02 '19 at 10:04
  • _Yes, but I am having problem at how to convert the string to a char array_ ??? [`std::string::c_str()`](https://en.cppreference.com/w/cpp/string/basic_string/c_str) (and may be `std::string::size()`) should do the job. – Scheff's Cat Apr 02 '19 at 10:05

1 Answers1

0

I think this is what you are looking for:

char * toJSON(int const id, std::string const& name)
{
    std::string json = "{\"id\":" + std::to_string(id) + ", \"name\":\"" + name + "\"}";

    char * arr = new char[json.length() + 1 /* terminating 0 */];

    strcpy_s(arr, json.length() + 1, json.c_str());

    return arr;
}

Don't forget to delete the array after you are done using it.

FloIsAwsm
  • 156
  • 1
  • 5