Parsing a curl json response and using response to build another request Parsing a curl json response and using response to build another request curl curl

Parsing a curl json response and using response to build another request


  1. On OS X you can use the system Perl:

     curl -sS http://xkcd.com/info.0.json | /usr/bin/perl -pe 's/.*"num": ([0-9]+).*/\1/'
  2. You can save the output to a variable with command substitution:

    num=$(curl -sS http://xkcd.com/info.0.json | /usr/bin/perl -pe 's/.*"num": ([0-9]+).*/\1/')curl -sS "http://xkcd.com/${num}/info.0.json"

    or more concisely, two-in-one, albeit not very readable:

    curl -sS "http://xkcd.com/$(curl -sS http://xkcd.com/info.0.json | /usr/bin/perl -pe 's/.*"num": ([0-9]+).*/\1/')/info.0.json"

By the way, I highly recommend jq as the command line JSON processor. To extract num with jq, it's as simple as

curl -sS http://xkcd.com/info.0.json | jq '.num'

and although you didn't ask for it, here's a simple one-liner with jq that extracts the URI of the latest image:

curl -sS "http://xkcd.com/$(curl -sS http://xkcd.com/info.0.json | jq '.num')/info.0.json" | jq -r '.img'

Example output:

http://imgs.xkcd.com/comics/spice_girl.png