I want to write a script that takes in a single argument, a string that contains some json data, and (for sake of simplicity) prints something.
import argparse
import json
parser = argparse.ArgumentParser(description='json load and 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 I run this from command line I get an error because of the double quotes that I use to wrap the string ending up matching double quotes in the json:
python myscript.py -i "{ "Employees": "name name"}"
Unrecognized arguments Employees...
If I switch the json double quotes to single quotes, the json parser will not work.
How do I handle something like this?
Your code will work as expected if you change how you assign your input variable. Change this line:
inp = parser.parse_args()
to
inp = args.inputstring
parse_args()
returns an argparse.Namespace
object, so you need to retrieve the input from that object prior to passing it to the parser. In addition, you will need to escape the double quotes in your shell command. I get the expected output with the above change run with:
python myscript.py -i "{ \"Employees\": \"name name\"}"
You should escape the internal double quotes in the JSON:
python myscript.py -i "{ \"Employees\": \"name name\"}"
But looking at your code, there are a couple of other reasons it may not be working:
you're assigning args
and inp
the same value, return value of the function call: parser.parse_args()
. Perhaps you meant to assign inp = args.inputstring
you've tagged the question as python2 but looking at your print(...)
statement, it looks like you've written for python3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With