Skip to main content

uniparser2

PyPI Python CI License: MIT

Turn text into structured data with JSON rules. A declarative, self-describing parsing DSL: deterministic, side-effect-free, and readable by humans and LLMs.

[["css1", "text", "h1.article-title"], ["py", "normalize_space"]]

// "<h1>  Hello   world </h1>"  →  "Hello world"
  • Rules are data. A rule is JSON: diffable, storable, generated by an LLM, shipped without a release.
  • No side effects in the kernel. The kernel performs no I/O and knows nothing about the host; the same input and rule produce the same output. The only non-determinism is an explicit host udf.
  • Failures are diagnostics. A bad rule fails at compile time with a UP2-E* code, a JSON Pointer and a one-line fix.
  • Stories compose. A story is a map of named nodes: call one from another, iterate a list with each, and fetch through a host udf — the engine stays synchronous and pure.

Not "self-explanatory": a css1 stage still needs CSS. It is self-describing — the JSON carries the operator, action and parameters, so a reader (or an LLM) can see what a rule does without the implementation, and move it between projects as data.

Install
uv add uniparser2             # kernel: zero third-party dependencies
uv add "uniparser2[html]"     # css / css1 (selectolax)
uv add "uniparser2[all]"      # every operator except the code sandbox

Python ≥ 3.12. Each operator declares its own extra; a missing one fails with UP2-E1107 and the install line, never a silent wrong value.

Security: what a rule can and cannot do

A default install — including uniparser2[all] — carries no code execution. A chain can only call the operators and actions the registry declares. Custom logic enters through two explicit doors:

  • udf: the chain names a function the host registered beforehand; the chain contains no body.
  • code: an optional, language-level sandbox, not installed by default and not part of [all]; it is not OS-level isolation. The surfaces it lacks and the ones it merely blocks are listed in docs/specs/004 §11.3.

Either door is greppable in the frozen rule (udf / code); there is no hidden host table.

30-second tour: a chain

A chain is a JSON array of stages [operator, action, parameter]:

import uniparser2 as up2

chain = [["css1", "text", "h1"], ["py", "normalize_space"]]
outcome = up2.eval_field(up2.compile_field(chain), "<h1>  Hello   world </h1>")
print(outcome)  # Ok(value='Hello world')

A query that matches nothing is a value ("" / [] / None), not an error; a bad stage stops the chain with a code. The CLI gives the same run plus compile-time validation:

uv run up2 lint chain.json
uv run up2 trial chain.json --input 'text=<h1>  Hello   world </h1>' --json
# {"state": "ok", "value": "Hello world"}
Stories: nodes that call each other

A story is {"globals": {...}, "nodes": {...}}. A node body is a chain (array; [] is identity) or a field map (object). A chain calls another node with ["node", name]; a field map evaluates every field on the node input, writes every result into $locals, and puts the fields without a _ prefix into the product. ["type", name] constructs a host-registered type from the value, at any stage of a chain.

{
  "globals": {"base_url": "https://quotes.toscrape.com"},
  "nodes": {
    "authors": [["node", "links"], ["each", [["node", "author"]]]],
    "links": [
      ["py", "strip"], ["ctx", "dict", {"url": "obj"}],
      ["udf", "fetch"], ["py", "getattr", "text"],
      ["css", "@href", "div.quote a[href^='/author/']"], ["py", "uniq"],
      ["each", [["py", "urljoin", "$globals.base_url"]]]
    ],
    "author": [
      ["ctx", "dict", {"url": "obj"}],
      ["udf", "fetch"], ["node", "fields"], ["type", "Author"]
    ],
    "fields": {
      "url": [["py", "getattr", "url"]],
      "name": [["py", "getattr", "text"], ["css1", "text", "h3.author-title"],
               ["py", "normalize_space"]]
    }
  }
}
import uniparser2 as up2

up2.register_type("Author", Author)  # a constructor: its instance flows mid-chain
product = up2.run(
    story, "authors", "https://quotes.toscrape.com", udfs={"fetch": my_fetch}
)  # synchronous; `fetch` blocks

run(story, node=None, input=None, *, globals=None, udfs=None, types=None, trace=None) returns the node's product (the first node is the default). globals merges over the story's constants for that run; types merges over the process-wide type registry the same way udfs does. Nothing requires JSON: a response object, or a type stage's constructed instance, flows mid-chain, is read with py.getattr, and is exactly what run answers. fetch takes a request object ({"url": …}); ["ctx","dict",{"url":"obj"}] builds one from the current value.

The GitHub pinned example (tested in the suite)

This is the template the test suite runs offline against fixtures (tests/chains/test_story.py): fetch a profile, take the first pinned item, fetch its detail page, and read the status code plus an [class*="Actions"] text.

{
  "globals": {"base_url": "https://github.com"},
  "nodes": {
    "pinned": [
      ["node", "list"],
      ["each", [["udf", "claim"]]],
      ["py", "filter"],
      ["py", "first"],
      ["node", "detail"]
    ],
    "list": [
      ["py", "strip"],
      ["ctx", "dict", {"url": "obj"}],
      ["udf", "fetch"],
      ["py", "getattr", "text"],
      ["css", "nodes", "div.js-pinned-items-reorder-container ol > li"],
      ["each", {"url": [["css1", "@href", "a"],
                        ["py", "urljoin", "$globals.base_url"]]}]
    ],
    "detail": [
      ["node", "detail_request"],
      ["udf", "fetch"],
      ["py", "sleep", 2],
      ["node", "detail_parse"]
    ],
    "detail_request": {"url": [["py", "getitem", "url"]]},
    "detail_parse": {
      "url": [["py", "getattr", "url"]],
      "status": [["py", "getattr", "status_code"]],
      "actions": [
        ["py", "getattr", "text"],
        ["css1", "text", "[class*=\"Actions\"]"],
        ["py", "normalize_space"]
      ]
    }
  }
}
import uniparser2 as up2
from uniparser2.net import RequestCache, fetch

cache = RequestCache()
seen: set[str] = set()


def cached_fetch(request):
    hit = cache.get(request)
    if hit is not None:
        return hit
    response = fetch(request)
    cache.put(request, response)
    return response


def claim(item):
    # Pretend this is the external dedupe store: a real one asks the DB/Redis.
    # The toy answers the item on first sight, None on a repeat; `py.filter` drops the None.
    if item["url"] in seen:
        return None
    seen.add(item["url"])
    return item


product = up2.run(
    story,
    "pinned",
    "https://github.com/ClericPy",
    udfs={"fetch": cached_fetch, "claim": claim},
)
# {"url": "https://github.com/ClericPy/awesome", "status": 200, "actions": "Actions"}

The offline fixture for this example carries the same pinned URL twice: claim answers the first one and None for the second, and py.filter removes the None before first/detail run. A real dedupe is a udf over the external store — that is the only IO in this pattern; the chain stays pure. The toy uses a set rather than a coin flip so the documented product stays reproducible.

To fetch every pinned item, keep the claim/filter before the fan-out and replace ["py", "first"] with an each over the detail node, pausing after it:

"pinned": [
  ["node", "list"], ["each", [["udf", "claim"]]], ["py", "filter"],
  ["each", [["node", "detail"], ["py", "sleep", 2]]]
]

The selectors are site-specific; fetch is not built in — it is the conventional name for the host's downloader.

More ETL examples

Eleven runnable stories live in examples/etl/: CSV rows, log lines, JSON orders, an HTML table, an XML feed, one article, dedupe/sort, a typed invoice, a host udf, nested node calls, and a nullable JSON field. Each case is story.json + input.txt + expected.json; uv run pytest tests/examples -q runs every one and compares it with its committed product. They are offline: no network, no store.

Operators

12 operators, 81 (operator, action) pairs; the registry is the authority, so ask it:

uv run up2 ops --json     # arity, slots, actions, parameter schema, dependencies, availability
Operator Engine (extra) Actions
css / css1 selectolax ([html]) text · html · outer · @<attr> · remove · self · nodes — all matches vs. first match
xpath lxml ([xml]) text · self · nodes
json jmespath ([json]) get — a jmespath expression
re stdlib search · findall · sub
py stdlib 48 allowlisted functions: text, collections, URL, time, encoding, conversion, predicates, filter, sleep
ctx stdlib get · set · del · dict · list (scope reads and writes)
each stdlib one field map or one chain per element of a list
udf host-registered any function in the run's table; DTO / * / ** / one explicit argument
node story call another node with the current value as its $in
type story construct a registered type from the value, at any stage
code pydantic-monty ([code], not in [all]) run — in-chain code in a language-level sandbox

py has no eval / exec / import; udf is the only way host code enters. The kernel is the standard library only and performs no I/O.

CLI and the template store
uv run up2 ops [--json]                 # the registry: write chains against this, not memory
uv run up2 lint site.json               # compile-time validation (does not execute)
uv run up2 trial site.json --node pinned --input text=@page.html --json
uv run up2 trial site.json --node pinned --trace    # one line per evaluated stage
uv run up2 conformance --check          # every declared pair/code has a visible test

A story that calls a udf needs a host; the CLI has none, so up2 trial reports UP2-E1010 for it — run it through a host recipe, or use up2 snapshot / up2 test with a filled request cache.

A finished rule is stored under a business identity (04 §1–§6): publish is the only write entry point, it lints again before writing, keeps one row per (root_domain, tpl_key) and appends a fingerprint to an append-only audit.

export UP2_HOME=~/.uniparser2          # UP2_STORE=sqlite for SQLite
uv run up2 publish site.json --domain example.com --key 政府文件列表 --actor llm:claude --source agent
uv run up2 get example.com 政府文件列表      # the row + its fingerprint
uv run up2 audit example.com 政府文件列表    # who changed it to which fingerprint, when
uv run up2 snapshot site.json --domain … --key … --case list-2026-09 --accept
uv run up2 test example.com 政府文件列表     # a mismatch prints a JSON Pointer difference
Status and roadmap

0.9.0. L1 (the operator layer) is complete and mechanically audited. L2 is the story model: globals + nodes, node calls, field maps and $locals, ["type", …], the synchronous run facade, and fetch as a host udf. L3's template store is in: file and SQLite implementations, fingerprints, append-only audit, and the publish / get / audit / snapshot / test / doctor commands. The committed samples/*/site.json and their hosts run end to end.

Not there yet: up2 list, the in-place trial UI (006, design only), ADRs, pagination loops and first_ok fallback groups (deferred changes). See docs/specs/007 §3.

The public API is compile_field / compile_stage / compile_story / eval_field / run plus the value, scope and trace types. The store is its own layer, uniparser2.store.

Development
uv sync
uv run ruff format --check
uv run ruff check
uv run mypy
uv run pytest --cov=uniparser2.core --cov-fail-under=95   # `-n 4` for a parallel local run
uv run up2 conformance --check

The 8 design notes live in docs/specs/ (index in docs/README.md) and are the source of truth for interfaces and DSL syntax. uv run python demo.py shows the operator layer; tools/demo_report.py regenerates the machine-written catalogue. The operator table above is a summary — the registry (up2 ops --json) is the authority.

Documentation

License

MIT. See LICENSE.

Metadata

Release files for uniparser2 0.9.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for uniparser2 0.9.0
File Size Uploaded Provenance Actions
uniparser2-0.9.0.tar.gz 241.1 kB Without provenance Details for uniparser2-0.9.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for uniparser2 0.9.0
File Interpreter ABI Platform Actions
uniparser2-0.9.0-py3-none-any.whl Python 3 none any Details for uniparser2-0.9.0-py3-none-any.whl

Total release size: 394.1 kB

Release files / uniparser2-0.9.0.tar.gz

Download URL uniparser2-0.9.0.tar.gz
Size 241.1 kB
Tags Source
SHA-256 checksum
How to use checksums
d26c347b52ce5ba213eb2fa667835ac58e278259daa370f8a74065e3fe51b9ce
BLAKE2b-256 checksum
How to use checksums
b0c333d61bc373a92320dff434737652fd4d1ed78817150c709a46cbe8756f18
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.3 {"installer":{"name":"uv","version":"0.11.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / uniparser2-0.9.0-py3-none-any.whl

Download URL uniparser2-0.9.0-py3-none-any.whl
Size 153.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a21932114ef56cbf8e0ad7607893a7dba15818a0d960dd3a95c6bb20b78ae6a2
BLAKE2b-256 checksum
How to use checksums
ea19ec499e37907b868373518bed17db574d18ac76038fba27786b0e33e0e413
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.3 {"installer":{"name":"uv","version":"0.11.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for uniparser2 0.9.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page