Skip to content
This repository has been archived by the owner on Dec 23, 2019. It is now read-only.

JSON Templater

Dave Allen edited this page Jul 23, 2013 · 1 revision

The JSON Templater (json_templater.js) is a module that aids with templating csv data to according to a specified JSON template. To understand how this module works, I recommend first looking at the json_templater_spec.

Combining Headers to Data

The function combineHeadersToData(cols, data) combines an array of column headers, and some data (an array of arrays, each array with length same as column headers array) and maps them into an array of javascript object. A simple example from the spec illustrates this:

it("produces the expected array of objects", function () {
  var cols = ["name1", "name2"];
  var data = [
    [1, 2],
    [3, 4]
  ];
  var expected = [
    {name1: 1, name2: 2},
    {name1: 3, name2: 4}
  ];
  expect(ArrayToJSON.combineHeadersToData(cols, data)).toEqual(expected);
});

Applying a template to a data set

After having obtained mapped objects with data mapped to column headers, we can apply a template to this newly mapped data. The function used for this is applyTemplateToDataSet(mappedData, jsonTemplate). This way, the data will be mapped to fit with a particular template. This works for the general case of an arbitrarily nested template. The below example from the spec should clarify:

describe("When the combined header-data and template are combined", function () {
  it("produces the expected array of objects", function () {
    var data = [
      {name1: 1, name2: 2},
      {name1: 3, name2: 4}
    ];
    var template = {
      key1:  {
        "columnName": "name1",
        "type":       "integer",
        "optional":   true
      },
      stuff: {
        key2: {
          "columnName": "name2"}
      }
    };
    var combinedData = ArrayToJSON.applyTemplateToDataSet(data, template);
    var expectedData = [
      {key1: 1, stuff: {key2: 2}},
      {key1: 3, stuff: {key2: 4}}
    ];
    expect(combinedData).toEqual(expectedData);
  });
});

More complex examples can be found in the spec file. There are also examples with some more realistic data.

Use and reuse

Currently, this module is used to aid in manifest reading; when a csv file is loaded, we convert the csv data into a format that can be understood by S2. The JSON Templater can be reused in any situation where templating is required to map data to form in which S2 can make necessary updates.