c++jsonparsingrapidjson

Parsing path in JSON


I'm trying to pass a JSON object containing a path from my frontend (Node) to the backend (C++) using RapidJSON, like so:

#include <iostream>
#include "rapidjson/document.h"

int main() {
  const char* json1 = "{\"path\":\"C:\\test.file\"}";                     // works
  const char* json2 = "{\"path\":\"C:\\fol der\\test.file\"}";            // works
  const char* json3 = "{\"path\":\"C:\\fol der\\Test.file\"}";            // ERROR!
  const char* json4 = "{\"path\":\"C:\\few dol\\test.file\"}";            // ERROR!
  const char* json5 = "{\"path\":\"C:\\folder\\anotherOne\\test.file\"}"; // ERROR!
  rapidjson::Document d;
  d.Parse(json3);    // works using json1 or json2
  assert(d.HasMember("path"));
  std::string pathString = d["path"].GetString();
  return 0;
}

The first two strings work. However, I can't get any longer paths to work and even capitalization is giving me trouble (the only difference between json2 and json3 is the "T").

How do I properly pass and parse paths (Windows and maybe Linux)?

Thank you in advance!

Edit: I just tried nlohman's JSON library and have the same problem.

How do I pass paths in JSON???


Solution

  • If you print your json variables you will get the following (C++ interprets the escape characters):

    json1: {"path":"C:\test.file"}
    json2: {"path":"C:\fol der\test.file"}
    json3: {"path":"C:\fol der\Test.file"}
    json4: {"path":"C:\few dol\test.file"}
    json5: {"path":"C:\folder\anotherOne\test.file"}
    

    Now you can test these json in any tool like https://jsonlint.com/, you will get errors. the reason for error is that the strings represented by "path" in the case of json3 and json5 are not valid string because of invalid escape characters present in them.

    Here is the list of escape sequences per string:
    json1 has \t
    json2 has \f and \t
    json3 has \f and \T
    json4 has \f and \t
    json5 has \f and \a and \t

    Among all of these escape characters, \T and \a are invalid and hence json3 and json5 are invalid as well.

    Now, if you want to parse it properly, then one simple way could be using four backslashes \\\\ for example:

    const char* json3 = "{\"path\":\"C:\\\\fol der\\\\Test.file\"}";
    

    which will be equivalent to C:\fol der\Test.file