OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Summarize finite numbers in a local JSON array

Python

Read a local JSON array of finite numbers, reject booleans and other invalid values, and print its count, minimum, maximum, and arithmetic mean.

Python code excerpt: Summarize finite numbers in a local JSON array. Version 0.1.0. Read the full recipe for code, sources and recorded test scope.

Use this small offline CLI to summarize numeric observations already saved in a JSON file, or supplied through standard input. It does not contact or test an external service, and the result describes only the provided data.

Before you start

  • Python 3.12 is the intended runner; the cited Python 3.12 documentation describes the standard-library `json` module and finite-value concerns for statistical data.
  • Provide a UTF-8 JSON file path or pipe one JSON document to stdin. The top-level value must be an array.
  • Every array item must be a finite integer or float. Booleans, strings, null, arrays, objects, NaN, and infinities are rejected.
  • The summary is only about the saved values supplied to the program; it is not a live-service check or financial advice.

Build and check

  1. Save the code as `summarize_numbers.py`.
  2. Create a synthetic fixture containing `[2, 4, 6]` and run `python3.12 summarize_numbers.py observations.json`.
  3. Confirm the displayed count, minimum, maximum, and mean match the fixture.
  4. Try an empty array, malformed JSON, a non-array top-level value, a boolean or string element, and a non-finite number; confirm empty input is explicit and invalid input exits with an error.
  5. Run with a nonexistent file path and confirm the missing-file error is written to stderr.

Limits to understand

  • This reports descriptive statistics for only the values supplied; it does not establish whether observations are representative or current.
  • The mean may be sensitive to outliers. No filtering, coercion, or missing-value imputation is performed.
  • Parsing untrusted JSON can consume significant CPU or memory; use appropriately small local input files.
  • A finite input set can still produce an unrepresentable floating-point mean for extreme values; that case is reported as an error.

What this example adds

The script accepts either a file path or stdin, gives empty arrays an explicit result instead of attempting min/max or mean, and reports malformed JSON, wrong top-level types, invalid elements, and missing files as readable errors on stderr with a nonzero exit status. It validates JSON constants such as NaN and Infinity, as well as numeric values, and checks that the computed mean remains finite. Results go to stdout only. The processing is local and read-only; it summarizes saved observations, not a live service or current data.

Run it

Save as `summarize_numbers.py`, then run `python3.12 summarize_numbers.py observations.json` or pipe input with `printf '[2, 4, 6]\n' | python3.12 summarize_numbers.py`. The intended runner is Python 3.12; no other minimum-version claim is made. There are no network calls, retries, or timeout requirement.

Example input

[2, 4, 6]

Expected output

count: 3
min: 2
max: 6
mean: 4.0
INSPECT THE SCRIPT

Inspect, copy and run the documented checks.

This browser preview builds code locally. It does not contact an API or run the code.

Default example ready.

Python example
# SPDX-License-Identifier: MIT
# Copyright (c) 2026 OpenViST contributors
import argparse
import json
import math
import pathlib
import sys


def reject_nonfinite_constant(value):
    raise ValueError(f"non-finite JSON number is not allowed: {value}")


def main():
    parser = argparse.ArgumentParser(
        description="Summarize a JSON array of finite numbers from a file or stdin."
    )
    parser.add_argument(
        "file",
        nargs="?",
        help="JSON file to read; omit this argument to read stdin",
    )
    args = parser.parse_args()

    try:
        if args.file:
            text = pathlib.Path(args.file).read_text(encoding="utf-8")
        else:
            text = sys.stdin.read()

        data = json.loads(text, parse_constant=reject_nonfinite_constant)
        if not isinstance(data, list):
            raise ValueError("top-level JSON value must be an array")

        values = []
        for index, value in enumerate(data, start=1):
            if isinstance(value, bool) or not isinstance(value, (int, float)):
                raise ValueError(f"item {index} must be a number, not a boolean or other value")
            if not math.isfinite(value):
                raise ValueError(f"item {index} must be finite")
            values.append(value)

        if not values:
            print("count: 0")
            print("min: n/a")
            print("max: n/a")
            print("mean: n/a")
            return 0

        mean = sum(values) / len(values)
        if not math.isfinite(mean):
            raise ValueError("mean is not finite; numeric values may be too large")

        print(f"count: {len(values)}")
        print(f"min: {min(values)}")
        print(f"max: {max(values)}")
        print(f"mean: {mean}")
        return 0
    except (OSError, UnicodeError, json.JSONDecodeError, ValueError, OverflowError) as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 2


if __name__ == "__main__":
    raise SystemExit(main())
What to verify after running
  • Run the normal synthetic example and verify all four output lines exactly.
  • Run with `[]` and verify `count: 0` and `n/a` for min, max, and mean.
  • Run malformed JSON and confirm a clear stderr message and nonzero exit status.
  • Run `[true]`, `["3"]`, `[null]`, and `[NaN]`; confirm each is rejected rather than coerced.
  • Run a top-level object such as `{}` and confirm it is rejected as not an array.
  • Use a nonexistent fixture path and confirm the missing-file condition is reported.

Request or format preview

Illustrative preview. No provider response, price or balance is fetched.

Change a setting to inspect the preview.

Official sources and related profiles

    Code license: MIT. Keep the license notice with your copy.

    Example version 0.1.0 · Documentation reviewed 2026-10-11.

    Executed 6 synthetic local fixture cases in isolated CPython 3.12.15 on GitHub Actions, without network access. Declared exit codes, output assertions and input integrity checks passed. Live services, installed third-party packages and production behavior remain outside scope. Editorial approval is still required.