'Pass json string to argument parser python
try to pass json string --model-config {'campaign_id':100500,'run_id':1} to parser:
parser = ArgumentParser(description="")
parser.add_argument(
'--model-config',
type=str,
help='valid json string to set up model config'
)
But in this case I can't use spaces between property names and between key value pairs, otherwise I get an error:
unrecognized arguments: 'run_id':1}
Also I need to use double quotes (instead of single quotes) for property names. But when I use double quotes I also get an error.
Do we have more convenient way to process json string?
Solution 1:[1]
Since JSON requires double quotes for string, wrap your option inside a single quote then pass the keys with double quotes. like:
'{"campaign_id":100500, "run_id":1}'
then your full command will be:
python yourfile.py --model-config '{"campaign_id":100500, "run_id":1}'
The option is in a valid format for JSON and can be deserialized with json.loads.
It is possible to use double quotes for the wrapper, but you need to escape the inside double quotes like:
"{\"campaign_id\":100500, \"run_id\":1}"
So I think first one is more convenient.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
