I have a CLI written with argparse
and I was wondering if there was a way to produce a JSON schema from the ArgumentParser
? The thought behind this being to distribute the JSON schema to extensions interfacing with the application, thus removing the need for each extension to write and maintain their own schema.
My idea was to
- Convert the
argparse.ArgumentParser
to Python dictionary or JSON file - and then pass that into a JSON schema generator
Example
import argparse
from genson import SchemaBuilder
parser = argparse.ArgumentParser(
description="Some description", prog="myprog", usage="myprog [options]"
)
parser.add_argument(
"-v",
"--version",
action="store_true",
help="Print server version number and exit",
)
parser.add_argument(
"-c",
"--config",
type=str,
default=".fortls",
help="Configuration options file (default file name: %(default)s)",
)
args = vars(parser.parse_args(""))
# Generate schema
builder = SchemaBuilder()
builder.add_schema({"type": "object", "properties": {}})
for k, v in args.items():
builder.add_object({k: v})
print(builder.to_json(indent=2))
Output
{
"$schema": "http://json-schema.org/schema#",
"type": "object",
"properties": {
"version": {
"type": "boolean"
},
"config": {
"type": "string"
}
}
}
However, I quickly realised that calling vars(parser().parse_args(""))
to convert the CLI into a dictionary resulted into a lot of information being lost, like descriptions and required.
Is there another way of doing this? I am open to swappingargparse
with some other CLI if it would make generating a schema easier.