pass a json string as an argument to Python script causes quotes problems -
i want write script takes in single argument, string contains json data, , (for sake of simplicity) prints something.
import argparse import json parser = argparse.argumentparser(description='json load , print') parser.add_argument('-i','--inputstring', help='input string in json format',required=true) args = parser.parse_args() inp = parser.parse_args() data = json.loads(inp) print(data['employees'])
when run command line error because of double quotes use wrap string ending matching double quotes in json:
python myscript.py -i "{ "employees": "name name"}" unrecognized arguments employees...
if switch json double quotes single quotes, json parser not work.
how handle this?
your code work expected if change how assign input variable. change line:
inp = parser.parse_args()
to
inp = args.inputstring
parse_args()
returns argparse.namespace
object, need retrieve input object prior passing parser. in addition, need escape double quotes in shell command. expected output above change run with:
python myscript.py -i "{ \"employees\": \"name name\"}"
Comments
Post a Comment