Skip to content Skip to sidebar Skip to footer

Save Json Outputted From A Url To A File

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

Solution 1:

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())

Solution 2:

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

Solution 3:

Solution 4:

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

InputStreaminput=null;
OutputStreamoutput=null;
try {
    input = newURL("http://search.twitter.com/search.json?q=hi").openStream();
    output = newFileOutputStream("/output.json");
    byte[] buffer = newbyte[1024];
    for (intlength=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:

Solution 5:

In shell:

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

Post a Comment for "Save Json Outputted From A Url To A File"