MRC/Tutorials/JSON Parsing

From Control Systems Technology Group
Revision as of 08:01, 18 May 2018 by WKuijpe1 (talk | contribs) (Created page with '= Saving to File = In the Hospital Challenge you are free to create one or two executables (the second one is started after parking). With having two executables or restarting in…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Saving to File

In the Hospital Challenge you are free to create one or two executables (the second one is started after parking). With having two executables or restarting in the search phase, you will have to "save" the map you made to some location which is not discarded after termination of the executable. For this purpose and maybe debugging purposes you might one to create a text file containing your worldmodel. One could simply write values to a text file ([[1]]), in this tutorial we will apply a bit more structure to such a file.

JSON

JSON JavaScript Object Notation ([[2]]) is a data-interchange format which is both easily readable and easily interpretable for humans and machines. JSON itself is a format, it does not describe how to put information in a file, only how the information should be formatted.

Example - Writing

To get you started with JSON, start-up company RUVU ([[3]]) created this simple example for you to explain you JSON. Suppose we are interested in storing (an array of) Corners, Corners are defined by

struct Corner
{
  double x_;
  double y_;

  Corner(double x, double y) : x_(x), y_(y)
  {
  }
};

In the case of the example, we would like to send two corners in an array, so in our map-building software we have somewhere created an array of corners

// building the data
std::vector<Corner> corners;
corners.push_back(Corner(3, 4));
corners.push_back(Corner(5, 6));

Using a JSON parser ([[4]]), this information is put into the JSON format

// copy the data into a json object
json j;
for (auto corner : corners)
{
  json c = { { "x", corner.x_ }, { "y", corner.y_ } };
  j.push_back(c);
}
// serialize the json to a file
std::ofstream output("corners.json");
output << std::setw(4) << j << std::endl;

and after that the JSON object created j, is printed to a file, using a output file stream ([[5]]). The array of corners is now stored in the file.

Example - Reading

After your executable has been restarted, or your second executable has been started, you would like to read the information in the file just created.