How to parse JSON passed on the command line?

yupeng zhang universeroc at gmail.com
Thu Nov 7 07:09:49 CET 2013


在 2013年11月7日星期四UTC+8上午11时53分09秒,Anthony Papillion写道:
> 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"}
> 
> 
> 
> 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}
> 
> 
> 
> Now, for the harder part. When I try to PARSE this JSON using this code:
> 
> 
> 
> json_string = json.loads(sys.argv[1])
> 
> 
> 
> I get an error saying that "No JSON object could be decoded".  Even
> 
> though this looks like valid JSON and was generated by a JSON generator.
> 
> 
> 
> Can anyone tell me what I'm doing wrong? Basically, I want to eventually
> 
> get the value of url into a string.
> 
> 
> 
> Thanks!
> 
> anthony

Hi Anthony Papillion.
I'm fresh to Python, but I do love its short simple and graceful.
I've solved your problem. You could try the code below:

getargfromcli.py "\"{'url':'http://www.google.com'}\""

AS command line will strip your ".
>From the Python document, we could get the info as:
json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')

the json.loads' argument should be string. Try it:)



More information about the Python-list mailing list