GitHub

json_pointer

API reference for json_pointer.

JSON Pointer tokens and URI fragments (RFC 6901, Effect's JsonPointer).

A JSON Pointer separates tokens with /, so a token escapes ~ as ~0 and / as ~1. A URI fragment percent-encodes the escaped pointer as JavaScript's encodeURI does, with # encoded too::

json_pointer.escape_token("a/b")                   # "a~1b"
json_pointer.parse_uri_fragment("#/users/a~1b")    # ["users", "a/b"]
json_pointer.format_uri_fragment(["a b", "Rate%"]) # "#/a%20b/Rate%25"

Functions

escape_token

escape_token(token) -> str

token with ~ as ~0 and / as ~1 (~ first, so nothing is escaped twice).

ParameterTypeDescription
tokenstr

Returns str

def escape_token(token: str) -> str:
    """``token`` with ``~`` as ``~0`` and ``/`` as ``~1`` (``~`` first, so
    nothing is escaped twice)."""
    return token.replace("~", "~0").replace("/", "~1")

unescape_token

unescape_token(token) -> str

The inverse of escape_token: ~1 to /, then ~0 to ~.

ParameterTypeDescription
tokenstr

Returns str

def unescape_token(token: str) -> str:
    """The inverse of ``escape_token``: ``~1`` to ``/``, then ``~0`` to ``~``."""
    return token.replace("~1", "/").replace("~0", "~")

parse_uri_fragment

parse_uri_fragment(fragment) -> list[str] | None

The tokens of a JSON Pointer URI fragment ("" and "#" are the root, []), percent-decoded and then unescaped. None for anything that is not a fragment, holds a character needing percent-encoding, or has an invalid ~ escape.

ParameterTypeDescription
fragmentstr

Returns list[str] | None

def parse_uri_fragment(fragment: str) -> list[str] | None:
    """The tokens of a JSON Pointer URI fragment (``""`` and ``"#"`` are the
    root, ``[]``), percent-decoded and then unescaped. ``None`` for anything
    that is not a fragment, holds a character needing percent-encoding, or
    has an invalid ``~`` escape."""
    pointer = _decode_uri_fragment(fragment)
    if pointer is None:
        return None
    if not pointer:
        return []
    return [unescape_token(token) for token in pointer[1:].split("/")]

format_uri_fragment

format_uri_fragment(path) -> str

path as a URI fragment: each token escaped, then percent-encoded; the empty path is "#". A token with a lone surrogate raises ValueError.

ParameterTypeDescription
pathSequence[str]

Returns str

def format_uri_fragment(path: Sequence[str]) -> str:
    """``path`` as a URI fragment: each token escaped, then percent-encoded;
    the empty path is ``"#"``. A token with a lone surrogate raises
    ``ValueError``."""
    return "#" + "".join(f"/{_format_uri_fragment_token(token)}" for token in path)