OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Resolve a JSON Pointer without evaluating expressions

Python

Read one JSON value through a restricted RFC 6901 string pointer.

Python code excerpt: Resolve a JSON Pointer without evaluating expressions. Version 1.0.0. Read the full recipe for code, sources and recorded test scope.

Read one JSON value through a restricted RFC 6901 string pointer. This stdin-based Python CLI processes one bounded JSON request and returns the documented JSON result. It does not execute jobs or contact external services. Inspect its limits before adapting it to an application.

Before you start

  • Python 3.12 standard library; no third-party packages. Verified with the recorded pinned runtime.
  • One UTF-8 JSON object on stdin, no command-line arguments. Maximum encoded request size is 20000 bytes.

Build and check

  1. Save the source as resolve-json-pointer-python.py.
  2. Save the example JSON below as request.json.
  3. Run python3 resolve-json-pointer-python.py < request.json.
  4. Compare the parsed JSON result with the expected output. Invalid input exits 2 with empty stdout and a generic stderr message.

Limits to understand

  • Input is limited to 20000 bytes, and the decoded pointer is limited to 1024 Unicode characters.
  • Non-integer JSON numbers use Python binary floating-point representation; values that become non-finite are rejected, and finite values may be rounded.
  • URI fragment pointers, URL decoding, array append tokens, mutation, and expression evaluation are not supported.
  • Input exactly {"document":any JSON value,"pointer":string}. Pointer is empty for root, otherwise begins slash. Decode each token ~1 to slash and ~0 to tilde in one pass; reject any other tilde escape.
  • Object tokens are exact keys. Array tokens must be 0 or a nonzero ASCII digit followed by ASCII digits; reject leading zeros, negative values, dash and out-of-range indices. Maximum pointer length 1024.
  • Output {"value":selected_value}; reject missing keys or traversing a scalar. No URI fragment form, URL decoding, mutation or dynamic evaluation.
  • The complete encoded input is limited to 20000 bytes; one additional byte can be read to detect overflow.
  • This is a bounded local helper. Passing the recorded cases does not verify every input, every Python version or an external integration.

Run it

python3 resolve-json-pointer-python.py < request.json

Example input

{"document": [1, 2], "pointer": ""}

Expected output

{"value":[1,2]}
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
import sys
import json
import math


class Invalid(Exception):
    pass


def reject(*args):
    raise Invalid()


def checked_string(value):
    if any(0xD800 <= ord(c) <= 0xDFFF for c in value):
        raise Invalid()
    return value


def finite_float(text):
    value = float(text)
    if not math.isfinite(value):
        raise Invalid()
    return value


def parse(text):
    decoder = json.JSONDecoder(parse_float=finite_float, parse_constant=reject)
    length = len(text)
    pos = 0

    def whitespace():
        nonlocal pos
        while pos < length and text[pos] in ' \t\r\n':
            pos += 1

    def value():
        nonlocal pos
        whitespace()
        if pos == length:
            raise Invalid()
        char = text[pos]
        if char == '{':
            pos += 1
            return {}, 'object'
        if char == '[':
            pos += 1
            return [], 'array'
        if char not in '"-0123456789tfn':
            raise Invalid()
        result, pos = decoder.raw_decode(text, pos)
        if isinstance(result, str):
            checked_string(result)
        return result, None

    root, kind = value()
    # Frames contain the container, its kind, and its grammar state.
    stack = [[root, kind, 'first']] if kind else []
    while stack:
        container, kind, state = stack[-1]
        whitespace()
        if pos == length:
            raise Invalid()
        char = text[pos]
        closing = '}' if kind == 'object' else ']'
        if state == 'after':
            if char == closing:
                pos += 1
                stack.pop()
            elif char == ',':
                pos += 1
                stack[-1][2] = 'next'
            else:
                raise Invalid()
            continue
        if state == 'first' and char == closing:
            pos += 1
            stack.pop()
            continue
        if kind == 'object':
            if char != '"':
                raise Invalid()
            key, pos = decoder.raw_decode(text, pos)
            checked_string(key)
            if key in container:
                raise Invalid()
            whitespace()
            if pos == length or text[pos] != ':':
                raise Invalid()
            pos += 1
            child, child_kind = value()
            container[key] = child
        else:
            child, child_kind = value()
            container.append(child)
        stack[-1][2] = 'after'
        if child_kind:
            stack.append([child, child_kind, 'first'])
    whitespace()
    if pos != length:
        raise Invalid()
    return root


def decode_token(token):
    result = []
    index = 0
    while index < len(token):
        char = token[index]
        if char != '~':
            result.append(char)
            index += 1
            continue
        if index + 1 == len(token):
            raise Invalid()
        escape = token[index + 1]
        if escape == '0':
            result.append('~')
        elif escape == '1':
            result.append('/')
        else:
            raise Invalid()
        index += 2
    return ''.join(result)


def resolve(request):
    if not isinstance(request, dict) or set(request) != {'document', 'pointer'}:
        raise Invalid()
    pointer = request['pointer']
    if not isinstance(pointer, str) or len(pointer) > 1024:
        raise Invalid()
    selected = request['document']
    if pointer == '':
        return selected
    if not pointer.startswith('/'):
        raise Invalid()
    # Decode every token before traversal, including tokens after a missing path.
    tokens = [decode_token(token) for token in pointer[1:].split('/')]
    for token in tokens:
        if isinstance(selected, dict):
            if token not in selected:
                raise Invalid()
            selected = selected[token]
        elif isinstance(selected, list):
            if not token or any(c < '0' or c > '9' for c in token):
                raise Invalid()
            if len(token) > 1 and token[0] == '0':
                raise Invalid()
            index = int(token)
            if index >= len(selected):
                raise Invalid()
            selected = selected[index]
        else:
            raise Invalid()
    return selected


def encode(value):
    # An explicit stack avoids imposing a nesting limit on JSON containers.
    output = []
    tasks = [('value', value)]
    while tasks:
        kind, item = tasks.pop()
        if kind == 'literal':
            output.append(item)
        elif isinstance(item, dict):
            output.append('{')
            tasks.append(('literal', '}'))
            entries = list(item.items())
            for index in range(len(entries) - 1, -1, -1):
                key, child = entries[index]
                tasks.append(('value', child))
                tasks.append(('literal', ':'))
                tasks.append(('value', key))
                if index:
                    tasks.append(('literal', ','))
        elif isinstance(item, list):
            output.append('[')
            tasks.append(('literal', ']'))
            for index in range(len(item) - 1, -1, -1):
                tasks.append(('value', item[index]))
                if index:
                    tasks.append(('literal', ','))
        else:
            output.append(json.dumps(item, ensure_ascii=True, allow_nan=False, separators=(',', ':')))
    return ''.join(output)


def main():
    try:
        if len(sys.argv) != 1:
            raise Invalid()
        data = sys.stdin.buffer.read(20001)
        if len(data) > 20000:
            raise Invalid()
        text = data.decode('utf-8', errors='strict')
        checked_string(text)
        # Permit all integer lengths possible within the input byte limit.
        sys.set_int_max_str_digits(0)
        request = parse(text)
        result = encode({'value': resolve(request)}) + '\n'
    except Exception:
        sys.stderr.write('Invalid input\n')
        return 2
    sys.stdout.write(result)
    return 0


if __name__ == '__main__':
    sys.exit(main())
What to verify after running
  • Run the documented example and compare the JSON result.
  • Confirm malformed requests exit 2 without copying input data into diagnostic messages.
  • 22 independent CLI cases passed on this exact source, including an unexpected-argument check.

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 1.0.0 · Documentation reviewed 2026-11-16.

    22 recorded CLI cases passed in rootless Docker on the pinned Python 3.12 runtime, with 512 MiB RAM, 1 CPU, no network, and read-only source. Other runtimes and all possible inputs are not verified.