3

I have simple C++ code that uses Boost library:

auto jsonStringPtr = jsonValuePtr->if_string();

How can I convert this value to std::string without quotes?

I tested this code:

std::string myString = boost::json::serialize(*jsonStringPtr);

but it contains quotes e.g. "abc" insted of abc... Any idea?

#edit

  • Boost: v1.76.0
  • C++: 20

Example:

boost::json::error_code errorCode;
boost::json::value jsonValue = boost::json::parse("{\"fff\": \"abc\"}", errorCode);

auto jsonString = jsonValue.as_object()["fff"].as_string();
std::string myString = boost::json::serialize(jsonString);
montjet
  • 525
  • 1
  • 4
  • 13

2 Answers2

6

I found the solution:

boost::json::value_to<std::string>(jsonValue)
montjet
  • 525
  • 1
  • 4
  • 13
  • 4
    Note that it's probably fine to let `ADL` find that, so you don't have to write `boost::json::value_to` but just `value_to` – sehe Sep 21 '21 at 15:20
  • Note that ADL won't work on a function call with explicit template arguments on any C++ version prior to C++20: https://stackoverflow.com/questions/2953684/why-doesnt-adl-find-function-templates – Daniel Schepler Feb 17 '23 at 22:20
0
auto jsonStringPtr = jsonValuePtr->as_string().c_str();
Brian Waters
  • 599
  • 4
  • 9
  • 19