<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#!/usr/bin/env python3

"""Extract data from a json document."""

import copy
import json
import sys
import typing


def usage(*, exit_code: int) -&gt; None:
    """Output a usage message."""
    if exit_code == 0:
        file_ = sys.stdout
    else:
        file_ = sys.stderr

    print(f"Usage: {sys.argv[0]} --input-separator i --output-separator o -- path/1 path/2", file=file_)

    sys.exit(exit_code)


def json_extract(*, json_document_str: str, paths: list[str], input_separator: str, output_separator: str):
    """Get n paths from a single json_document string."""
    json_document = json.loads(json_document_str)
    for path in paths:
        result = extract_one(json_document=json_document, input_separator=input_separator, path=path)
        print(result, end=output_separator)


def extract_one(*, json_document: typing.Any, path: str, input_separator: str) -&gt; typing.Any:
    """Get one path from a single json_document of dicts and lists."""
    current = copy.deepcopy(json_document)
    for path_part in path.split(input_separator):
        if isinstance(current, list):
            integer = int(path_part)
            current = current[integer]
        elif isinstance(current, dict):
            current = current[path_part]
        else:
            raise ValueError(f"Invalid type in json_document: {type(current)}")
    return current


def main() -&gt; None:
    """For the shell-callable functionality."""
    input_separator = "/"
    output_separator = "\n"
    while sys.argv[1:] and sys.argv[1].startswith("-"):
        if sys.argv[1] == "--":
            break
        elif sys.argv[1] == "--input-separator":
            input_separator = sys.argv[2]
            del sys.argv[1]
        elif sys.argv[1] == "--output-separator":
            output_separator = sys.argv[2]
            del sys.argv[1]
        elif sys.argv[1] in ("-h", "--help"):
            usage(exit_code=0)
        else:
            print(f"{sys.argv[0]}: unrecognized option: {sys.argv[1]}", file=sys.stderr)
            usage(exit_code=1)
        del sys.argv[1]

    json_document_str = sys.stdin.read()
    paths = sys.argv[1:]
    json_extract(
        json_document_str=json_document_str, paths=paths, input_separator=input_separator, output_separator=output_separator
    )


if __name__ == "__main__":
    main()
</pre></body></html>