How to create and export data

Open a python shell in interactive mode (run python3) and run the following commands in sequence.

First we’ll import the library and make a new store.

from ocdsmetricsanalysis.library import Store
store = Store("how-to-create-export.sqlite")

Currently the store is empty, as you can see by getting a list of current metrics.

print(store.get_metrics())

We’ll add our own metric!

store.add_metric("HATS", "How many people like hats?", "We ran a survey to find out.")
metric = store.get_metric("HATS")

Now we have our metric, but we need to add some observations to it.

metric.add_observation("obs1", measure=34, dimensions={'answer':'like'})
metric.add_observation("obs2", measure=15, dimensions={'answer':'neither like or dislike'})
metric.add_observation("obs3", measure=12, dimensions={'answer':'dislike'})

The first parameter is the id of the observation. This must be unique in the metric.

You can also pass other information such as financial data or unit information - see the reference for details.

Now our store contains some data - we can export this as JSON.

import json
json_data = metric.get_json()
print(json.dumps(json_data, indent=4))

You should see something like:

{
     "id": "HATS",
     "title": "How many people like hats?",
     "description": "We ran a survey to find out.",
     "observations": [
         {
             "id": "obs1",
             "dimensions": {
                 "answer": "like"
             },
             "measure": "34"
         },
         {
             "id": "obs2",
             "dimensions": {
                 "answer": "neither like or dislike"
             },
             "measure": "15"
         },
         {
             "id": "obs3",
             "dimensions": {
                 "answer": "dislike"
             },
             "measure": "12"
         }
     ]
}

You can save this to disk as normal

with open("output.json", "w") as fp:
    json.dump(json_data, fp, indent=4)