Created
December 16, 2025 10:58
-
-
Save iomarmochtar/26019cbec80d02ccb6a2f9bb2451c429 to your computer and use it in GitHub Desktop.
Utilizing jq cli to filter the dictionary object structure, it's like a yq but without to install additional tool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import subprocess | |
| import json | |
| import yaml | |
| import sys | |
| from pathlib import Path, PosixPath | |
| from typing import Any | |
| from argparse import ArgumentParser | |
| from pprint import pprint | |
| KV = dict[str, Any] | |
| def read_yaml(path: str | PosixPath) -> KV: | |
| with open(path, "r") as fh: | |
| return yaml.safe_load(fh.read()) | |
| def jq_filter(filter: str, data: KV) -> Any: | |
| json_input = json.dumps(data) | |
| process = subprocess.run( | |
| ["jq", filter], | |
| input=json_input.encode("utf-8"), | |
| stdout=subprocess.PIPE, | |
| stderr=subprocess.PIPE, | |
| ) | |
| if process.returncode != 0: | |
| raise RuntimeError(f"jq error: {process.stderr.decode('utf-8')}") | |
| output = process.stdout.decode("utf-8").strip() | |
| return json.loads(output) | |
| if __name__ == "__main__": | |
| argparse = ArgumentParser(prog="not_a_yq") | |
| argparse.add_argument("yq_query", help="jq filter") | |
| argparse.add_argument("yq_yml", help="path of yaml file") | |
| args = argparse.parse_args() | |
| yaml_path = Path(args.yq_yml) | |
| if not yaml_path.exists(): | |
| sys.stderr.write(f"{yaml_path} is not found\n") | |
| sys.exit(1) | |
| pprint( | |
| jq_filter(filter=args.yq_query, data=read_yaml(path=yaml_path)), | |
| indent=2 | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment