Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass a json string as an argument to Python script causes quotes problems

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?

like image 700
ADJ Avatar asked Nov 17 '16 16:11

ADJ


2 Answers

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\"}"
like image 92
Joel Avatar answered Sep 21 '22 22:09

Joel


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:

  1. 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

  2. you've tagged the question as python2 but looking at your print(...) statement, it looks like you've written for python3

like image 23
Rich Avatar answered Sep 22 '22 22:09

Rich