c++nlohmann-json

Double escaped value in a json response


After printing out a raw response(not parsed with nlohmann json) from an API. I get something like this:

{
  "Pages": {
    "Limit": 10,
    "CurrentPage": 1
  },
  "Messages": [
    {
      "Subject": "\"Some subject that is surrounded with escaped quotes and has double escaped escape sequences for example: \\u015b \"",
      "Body": "\"The body is structured in the same way\""
    },
    ...
  ],
  "Resources": {
    "Messages\\Unread": {
      "Url": "..."
    },
    ...
  }
}

After parsing

json data = json::parse(response);
std::cout << data["Messages"][0]["Subject"];

This outputs:

"Some subject with double quotes surrounding it and an single escaped escape sequences: \u015b" 

Why would a response look like that if the end goal is to display real characters not escape sequences. Is there a way to display this without having to manually unescape every value?

I tried to parse again a newly created json string that has the value of the response:

json parsed_subject_json = json::parse(R"(
            { 
                "Body":)" + (std::string)data["Messages"][0]["Body"] + R"(
            })"
        );

And then retrieving the value but this results in the same outcome.


Solution

  • I was able to "unescape" the json value. Thanks to nneonneo, who suggested parsing again with:

    json::parse(data["Messages"][0]["Subject"].template get<std::string>())
    

    I wonder why that didn't work when I tried wraping it as an object.