Save JSON outputted from a URL to a file


Question

How would I save JSON outputted by an URL to a file?

e.g from the Twitter search API (this http://search.twitter.com/search.json?q=hi)

Language isn't important.

edit // How would I then append further updates to EOF?

edit 2// Great answers guys really, but I accepted the one I thought was the most elegant.

1
14
10/23/2018 6:06:12 PM

Accepted Answer

This is easy in any language, but the mechanism varies. With wget and a shell:

wget 'http://search.twitter.com/search.json?q=hi' -O hi.json

To append:

wget 'http://search.twitter.com/search.json?q=hi' -O - >> hi.json

With Python:

urllib.urlretrieve('http://search.twitter.com/search.json?q=hi', 'hi.json')

To append:

hi_web = urllib2.urlopen('http://search.twitter.com/search.json?q=hi');
with open('hi.json', 'ab') as hi_file:
  hi_file.write(hi_web.read())
25
6/14/2010 9:14:32 PM

In PHP:

$outfile= 'result.json';
$url='http://search.twitter.com/search.json?q=hi';
$json = file_get_contents($url);
if($json) { 
    if(file_put_contents($outfile, $json, FILE_APPEND)) {
      echo "Saved JSON fetched from “{$url}” as “{$outfile}”.";
    }
    else {
      echo "Unable to save JSON to “{$outfile}”.";
    }
}
else {
   echo "Unable to fetch JSON from “{$url}”.";
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon