'How to parse JSON passed on the command line

I am trying to pass JSON parameters through command line in Python:

automation.py {"cmd":"sel_media","value":"5X7_photo_paper.p}

how can I extract the values sel_media and 5X7_photo_paper.p?

I used the following code, but it is not working:

cmdargs = str(sys.argv[1])
print cmdargs


Solution 1:[1]

Provided you pass actual valid JSON to the command line and quote it correctly, you can parse the value with the json module.

You need to quote the value properly, otherwise your shell or console will interpret the value instead:

automation.py '{"cmd":"sel_media","value":"5X7_photo_paper.p"}'

should be enough for a bash shell.

In Python, decode with json.loads():

import sys
import json

cmdargs = json.loads(sys.argv[1])
print cmdargs['cmd'], cmdargs['value']

Demo:

$ cat demo.py 
import sys
import json

cmdargs = json.loads(sys.argv[1])
print cmdargs['cmd'], cmdargs['value']

$ bin/python demo.py '{"cmd":"sel_media","value":"5X7_photo_paper.p"}'
sel_media 5X7_photo_paper.p

Solution 2:[2]

The above is generally correct, but I ran into issues with it when running on my own python script

python myscript.py '{"a":"1"}'

does not work directly in my terminal

so I did

python myscript.py '{\"a\":\"1\"}'

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 Martijn Pieters
Solution 2 Ethan Seow