Python doesn't require any non-standard libraries to do this:
import urllib
import urllib2
import json
import sys
inputphrase = sys.stdin.read()
terms = urllib.quote_plus(inputphrase.strip())
url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&filter=1&rsz=small&q=" + terms
data = urllib2.urlopen(url).read()
output = "[" + inputphrase + "](" + json.loads(data)["responseData"]["results"][0]["unescapedUrl"] + ")"
print output
The url
fields are percent-encoded twice, so %20
becomes %25%20
. You should get the unescapedUrl
instead.
I'm just using sed to "parse" the JSON in my urlalias script:
curl -s --get --data-urlencode q=example http://ajax.googleapis.com/ajax/services/search/web?v=1.0 | sed 's/"unescapedUrl":"\([^"]*\).*/\1/;s/.*GwebSearch",//'