views:

236

answers:

5

Hey Guys,

How would I save JSON outputed 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.

Thanks!

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. Thanks! :)

+3  A: 

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())
Matthew Flaschen
How would I then append further updates to EOF?
Ulkmun
+2  A: 

In shell:

wget -O output.json 'http://search.twitter.com/search.json?q=hi'
Ignacio Vazquez-Abrams
How would I then append further updates to EOF?
Ulkmun
Just output to stdout (`-`) and use the append redirection operator (`>>`).
Ignacio Vazquez-Abrams
`wget <URL> >> output.json`
Ether
+1  A: 

Here's the (verbose ;) ) Java variant:

InputStream input = null;
OutputStream output = null;
try {
    input = new URL("http://search.twitter.com/search.json?q=hi").openStream();
    output = new FileOutputStream("/output.json");
    byte[] buffer = new byte[1024];
    for (int length = 0; (length = input.read(buffer)) > 0;) {
        output.write(buffer, 0, length);
    }
    // Here you could append further stuff to `output` if necessary.
} finally {
    if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
    if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}

See also:

BalusC
How would I then append further updates to EOF?
Ulkmun
See the comment in the code example.
BalusC
+1  A: 

You can use CURL

curl -d "q=hi" http://search.twitter.com -o file1.txt
Bernie Perez
+1  A: 

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}”.";
}