uniparser2
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 hostudf— the engine stays synchronous and pure.
Not "self-explanatory": a
css1stage 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 indocs/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] ends a chain with a host-registered validator.
{
"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 validator, not a container
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, trace=None) returns the node's product
(the first node is the default). globals merges over the story's constants for that run. The exit and
a type stage require JSON; a response object may flow mid-chain and be read with py.getattr.
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 | validate a chain-tail product against a registered type |
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.7.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
docs/README.md— the design notes (00–07) and reference pages.docs/operator-reference.md— every action and its worked example.docs/report/up2-report.md— one case per covered pair, generated (the coverage check at the top names any pair still missing).
License
MIT. See LICENSE.
Metadata
Release files for uniparser2 0.7.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| uniparser2-0.7.1.tar.gz | 229.2 kB | Without provenance | Details for uniparser2-0.7.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| uniparser2-0.7.1-py3-none-any.whl | Python 3 | none | any | Details for uniparser2-0.7.1-py3-none-any.whl |
Total release size: 380.5 kB
Release files / uniparser2-0.7.1.tar.gz
| Download URL | uniparser2-0.7.1.tar.gz |
|---|---|
| Size | 229.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
bc1d14ebb7b94c9fed1fa248c99e144a8bb5d7390afc6afc92a20917a4eda87d
|
|
BLAKE2b-256 checksum How to use checksums |
14e880ef11a68916d14da321d469938cfd34009dc8669c7d83fba2d8f2c228b0
|
| 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.7.1-py3-none-any.whl
| Download URL | uniparser2-0.7.1-py3-none-any.whl |
|---|---|
| Size | 151.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
600c439b09b4050f0ac78a41d9db6a38d7c11d0e206513e9c68103590b81d943
|
|
BLAKE2b-256 checksum How to use checksums |
485d763b7a45a08fde2820f4d9d5fdcfe67790e651e8d1f52d1890d078b9bd93
|
| 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.7.1
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.