# write_results()

Write the results of an interrogated validation to a JSON file.

Usage

[Source](https://github.com/posit-dev/pointblank/blob/main/pointblank/validate.py#L1593-L1756)

``` python
write_results(
    validation,
    filename,
    path=None,
    metadata=None,
    run_id=None,
)
```

A results file holds one run of a validation, as plain JSON: the metadata of the run (the table name, label, start and end times, owner, …), any metadata you give in `metadata=`, and every step with its results. It's meant for keeping the results of many runs (e.g., a nightly job that writes a file per run), for reporting on them together with [`MultiValidate.from_files()`](../reference/MultiValidate.from_files.md#pointblank.MultiValidate.from_files), and for reading them in other tools. Read a results file back with [`read_results()`](../reference/read_results.md#pointblank.read_results), which gives a validation with all the reports of the original.

Unlike [`write_file()`](../reference/write_file.md#pointblank.write_file), which saves the validation object itself as a pickle, a results file holds no table and no data extracts, can be read by any version of Pointblank that supports its format version, and is safe to read from any source (reading it runs no code).

## Parameters

`validation: Validate`  
The interrogated [Validate](../reference/Validate.md#pointblank.Validate) object to write.

`filename: str`  
The name of the file to write. The `.json` extension is added if it's not in the name.

`path: str | Path | None = None`  
An optional directory to write the file to (it's created if it doesn't exist). By default, the file is written to the current working directory.

`metadata: dict[str, Any] | None = None`  
An optional dictionary of metadata for the run, e.g., `{"job": "nightly", "commit": "a1b2c"}`. It's written as is (its values can be any value a step can hold) and can be read back from the file, but it isn't shown in the reports.

`run_id: str | None = None`  
An optional ID for the run. By default, a new random ID (a UUID) is used. A validation read from a results file keeps the run ID and metadata of its file when it's written again, unless new ones are given.

## Returns

`None`  
This function doesn't return anything but writes the results file.

## The Results File Format

A results file is a JSON object with these fields:

- `format` (always `"pointblank-results"`) and `format_version` (an integer, now `1`): a newer format version is used only for changes that older versions of Pointblank couldn't read, and [read_results()](../reference/read_results.md#pointblank.read_results) raises an error for a format version newer than the ones it supports
- `run_id`, `pointblank_version` (the version that wrote the file), and [metadata](../reference/pointblank.SubmissionPackage.metadata.md)
- the metadata of the validation: `tbl_name`, `tbl_type`, `label`, `time_start` and `time_end` (ISO 8601 times), `lang`, `locale`, `owner`, `consumers`, `version`, `thresholds` (an object with the [warning](../reference/Validate.warning.md#pointblank.Validate.warning), [error](../reference/Validate.error.md#pointblank.Validate.error), and [critical](../reference/Validate.critical.md#pointblank.Validate.critical) levels), and `brief`
- `steps`: an array with an object per step, which has the fields of the steps in [get_json_report()](../reference/Validate.get_json_report.md#pointblank.Validate.get_json_report) (`i`, `assertion_type`, `column`, [values](../reference/MetadataPackage.md#pointblank.MetadataPackage.values), `n_passed`, [warning](../reference/Validate.warning.md#pointblank.Validate.warning), …), the step key (`step_key`, which identifies the step across runs), and a few more fields that the reports use (`missing`, `autobrief`, `expr_source`, `eval_error`, `failure_text`, and `notes`)

Values that JSON has no type for are written as an object with a `"$type"` field, which names the type of the value. These are kept as data:

- `{"$type": "col", "name": ...}` for [col()](../reference/col.md#pointblank.col) and `{"$type": "ref", "column": ...}` for [ref()](../reference/ref.md#pointblank.ref)
- `{"$type": "tuple", "items": [...]}`, `{"$type": "set", "items": [...]}`, and `{"$type": "dict", "items": [[key, value], ...]}` for a dictionary with keys that aren't strings
- `{"$type": "datetime", "value": ...}` (and `"date"` and `"time"`) with an ISO 8601 value, `{"$type": "timedelta", "seconds": ...}`, `{"$type": "decimal", "value": ...}`, `{"$type": "path", "value": ...}`, and `{"$type": "float", "value": "nan"}` (or `"inf"` and `"-inf"`)
- `{"$type": "thresholds", ...}`, `{"$type": "schema", "columns": [[name, dtype], ...]}`, and `{"$type": "seg_group", "segments": [...]}`

Values that can't be kept as data are written as a description, with a `text` field (and for some, a `fields` object): `"callable"` for a function (its source code), `"expr"` for an expression (its printed form, and the columns it uses), `"table"` for a table (its type), `"column_selector"`, `"bytes"`, and `"object"` for any other value (its class and printed form). The comparison results of a `tbl_match()` or `tbl_reconcile()` step are written as in [get_json_report()](../reference/Validate.get_json_report.md#pointblank.Validate.get_json_report), without samples of the differing rows.

## Examples

Let's interrogate a validation of the `small_table` dataset and write its results to a file, with some metadata about the run:

``` python
import pointblank as pb
import tempfile

validation = (
    pb.Validate(
        data=pb.load_dataset("small_table"),
        tbl_name="small_table",
        label="Nightly check",
        thresholds=(0.1, 0.25),
    )
    .col_vals_gt(columns="d", value=1000)
    .col_vals_le(columns="c", value=pb.col("d"))
    .col_vals_not_null(columns="c")
    .interrogate()
)

results_dir = tempfile.mkdtemp()
pb.write_results(validation, "nightly", path=results_dir, metadata={"job": "nightly"})
```

The file is plain JSON, so it can be read with any JSON reader. Here are a few of the fields of the run:

``` python
import json
import os

with open(os.path.join(results_dir, "nightly.json")) as f:
    record = json.load(f)

{key: record[key] for key in ("format_version", "tbl_name", "label", "metadata")}
```

    {'format_version': 1,
     'tbl_name': 'small_table',
     'label': 'Nightly check',
     'metadata': {'job': 'nightly'}}

And here are a few of the fields of the second step:

``` python
step = record["steps"][1]

{key: step[key] for key in ("assertion_type", "column", "values", "n_failed", "warning")}
```

    {'assertion_type': 'col_vals_le',
     'column': 'c',
     'values': {'$type': 'col', 'name': 'd'},
     'n_failed': 2,
     'warning': True}

The `value=pb.col("d")` of the step is written as `{"$type": "col", "name": "d"}`, so that it can be read back as a column reference (and not as the string `"d"`). To get a validation with all the reports from the file, use [read_results()](../reference/read_results.md#pointblank.read_results).

## See Also

[read_results()](../reference/read_results.md#pointblank.read_results)  
Read a validation's results from a file written with [write_results()](../reference/write_results.md#pointblank.write_results).

[from_files()](../reference/MultiValidate.from_files.md#pointblank.MultiValidate.from_files)  
Read several results files into one [MultiValidate](../reference/MultiValidate.md#pointblank.MultiValidate) object.

[write_file()](../reference/write_file.md#pointblank.write_file)  
Save a whole validation object to disk, including its table if wanted.
