How to parse JSON passed on the command line?

Chris Rebert clp2 at rebertia.com
Wed Nov 6 23:06:56 EST 2013


On Wed, Nov 6, 2013 at 7:53 PM, Anthony Papillion <papillion at gmail.com> wrote:
> Hello Everyone,
>
> I'm writing a little helper script in Python that will access a JSON
> formatted argument from the shell when it's called. The parameter will
> look like this:
>
> {"url":"http://www.google.com"}
>
> So, if my program is called "getargfromcli.py" the call will look like this:
>
> getargfromcli.py {"url":"http://www.google.com"}

You probably want
    getargfromcli.py '{"url":"http://www.google.com"}'
instead, so that your string of JSON is treated literally by the shell.

> In the case above, I assume my JSON string will be argv[1]. In fact,
> when I do
>
> print sys.argv[1]
>
> It works as expected and prints out the JSON string as expected like
> this: {url:http://www.google.com}

No, that's not JSON anymore! All the required quotation marks have
gone missing. The shell ate them.

Regards,
Chris



More information about the Python-list mailing list