0

Imagine that I have this json:

{
  "a":"b"
}

If I have a function in C++ that returns this json in string format, such as std::string getjson(), it would return stringified version of this json like:

"{\"a\":\"b\"}"

To be complete:

std::string getjson()
{
    return "{\"a\":\"b\"}";
}

myfavourite_jsonparser.parse(getjson());

This works.

Now imagine that the value of key in json contains a ":

{
  "a":"\"b"
}

How could I return this from std::string getjson() function?

3
  • "{\"a\":\"\\\"b\"}" or R"({"a":"\"b"})"? Commented Oct 8, 2020 at 8:01
  • 5
    Consider using raw string literals when embedding things in strings. Commented Oct 8, 2020 at 8:04
  • Or even better use a json library rather than trying to construct it by hand Commented Oct 8, 2020 at 8:28

1 Answer 1

3

Just as you escape a quote with a backslash (\" results in "), a backslash can be used to escape backslashes as well. So \\ results in \.

So if you want to output \", then escape like this: \\\".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.