How to parse JSON passed on the command line
Question: 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
    


Answer: Provided you pass actual valid JSON to the command line and quote it
correctly, you can parse the value with the [`json`
module](https://docs.python.org/2/library/json.html).

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()`](https://docs.python.org/2/library/json.html#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
    

