MRC/Tutorials/JSON Parsing

From Control Systems Technology Group
Revision as of 16:23, 18 May 2018 by WKuijpe1 (talk | contribs)
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 corners.json-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. We then read the file using an input stream ([[6]]) and we move the string from the corners.json-file into j.

// read the json object from a file
std::ifstream i("corners.json");
json j;
i >> j;

We have to be carefull that this code is robust for reading other kinds of files, therefore note the use of assert.

// copy the data from a json object
assert(j.is_array());
for (const auto& c : j)
{
  assert(c.is_object());
  assert(c.find("x") != c.end());  // check for key x
  assert(c.find("y") != c.end());  // check for key y
  corners.push_back(Corner(c["x"], c["y"]));
}

Full Example

The code-package attached below shows a full example for JSON parsing. File:JSONExample.zip