File size: 1,413 Bytes
d868d2e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import json
def main(
paths: list[str],
field: list[str],
format: str = "plain",
) -> None:
result = []
for path in paths:
with open(path, "r") as f:
data = json.load(f)
value = data
for key in field:
value = value.get(key)
if not isinstance(value, list):
value = [value]
result.extend(value)
if format == "plain":
print(",".join(map(str, result)))
elif format == "python":
result_str = str(result)
print(result_str.replace(" ", ""))
else:
raise ValueError(f"Unknown format: {format}")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description="Get a field from one or more JSON files and print to stdout."
)
parser.add_argument(
"paths",
type=lambda x: x.split(","),
help="Comma-separated list of paths to the JSON files to process.",
)
parser.add_argument(
"--field",
type=str,
required=True,
nargs="+",
help="Field to extract from the JSON files. Can be a nested field by providing multiple entries.",
)
parser.add_argument(
"--format",
type=str,
default="plain",
choices=["plain", "python"],
)
args = parser.parse_args()
kwargs = vars(args)
main(**kwargs)
|