Skip to contents

Aside from R code, tfrmt objects can be represented as machine-readable metadata in JSON format. This enables users to save formatting metadata to a database, or alternatively import templates stored as JSON files. There are several utilities available for seamless translation between tfrmt and JSON.

tfrmt to JSON

A tfrmt object can be converted to JSON using the tfrmt_to_json function. Suppose we have a basic tfrmt:

template_tfrmt <- tfrmt(
  group = grp,
  label = label,
  column = column,
  param = param,
  value=value,
  body_plan = body_plan(
    frmt_structure(group_val = ".default", 
                        label_val = ".default", 
                        frmt("xx.x")))
  ) 
template_tfrmt %>% print_mock_gt()
column1 column2 column3
grp_1


label_1 xx.x xx.x xx.x
label_2 xx.x xx.x xx.x
label_3 xx.x xx.x xx.x
grp_2


label_1 xx.x xx.x xx.x
label_2 xx.x xx.x xx.x
label_3 xx.x xx.x xx.x
grp_3


label_1 xx.x xx.x xx.x
label_2 xx.x xx.x xx.x
label_3 xx.x xx.x xx.x

We can pass this through tfrmt_to_json to convert to JSON metadata.

template_tfrmt %>%
  tfrmt_to_json()
#> {
#>   "group": ["grp"],
#>   "label": ["label"],
#>   "param": ["param"],
#>   "value": ["value"],
#>   "column": ["column"],
#>   "body_plan": [
#>     {
#>       "group_val": [".default"],
#>       "label_val": [".default"],
#>       "param_val": [".default"],
#>       "frmt": {
#>         "expression": ["xx.x"],
#>         "missing": {},
#>         "scientific": {},
#>         "transform": {}
#>       }
#>     }
#>   ]
#> }

This JSON can optionally be saved to a file by providing a file path as the second argument to the function:

tfrmt(
  group = grp,
  label = label,
  column = column,
  param = param,
  value=value,
  body_plan = body_plan(
    frmt_structure(group_val = ".default", 
                        label_val = ".default", 
                        frmt("xx.x")))
  ) %>%
  tfrmt_to_json(path = "template.JSON")

JSON to tfrmt

If a JSON file already exists, users can import this into R.

template_json <- json_to_tfrmt(path = "template.JSON")

Once available in the R session, users can optionally build on this template as needed.

template_json %>% 
  layer_tfrmt(
    tfrmt(title = "Custom title")
  ) %>% 
  print_mock_gt()
Custom title
column1 column2 column3
grp_1


label_1 xx.x xx.x xx.x
label_2 xx.x xx.x xx.x
label_3 xx.x xx.x xx.x
grp_2


label_1 xx.x xx.x xx.x
label_2 xx.x xx.x xx.x
label_3 xx.x xx.x xx.x
grp_3


label_1 xx.x xx.x xx.x
label_2 xx.x xx.x xx.x
label_3 xx.x xx.x xx.x