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.
Using the Chrome browser, go to the url with the json, then right click, then 'Inspect'. That brings up the Chrome devtools ui. From there go to 'Sources' and you will see the json file in the list. Then right click and you will be able to click 'Save as'.
Output: In this way, one can easily read a JSON response from a given URL by using urlopen() method to get the response and then use json. loads() to convert the response into a JSON object.
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())
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}”.";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With