Подтвердить что ты не робот

Сохранить JSON, выводимый из URL-адреса в файл

Как мне сохранить JSON, выводимый URL-адресом в файл?

например, из API поиска Twitter (это http://search.twitter.com/search.json?q=hi)

Язык не важен.

Спасибо!

edit//Как я могу добавить дополнительные обновления к EOF?

edit 2//Отличные ответы на парней, но я принял тот, который я считал самым элегантным. Благодарю!:)

4b9b3361

Ответ 1

Это легко на любом языке, но механизм меняется. С wget и оболочкой:

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

Чтобы добавить:

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

С Python:

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

Чтобы добавить:

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

Ответ 2

Здесь вариант (verbose;)) Java:

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) {}
}

См. также:

Ответ 3

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

Ответ 4

Вы можете использовать CURL

curl -d "q=hi" http://search.twitter.com -o file1.txt

Ответ 5

В оболочке:

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

Ответ 6

Вы можете использовать Jackson:

 ObjectMapper mapper = new ObjectMapper(); 
 Map<String,Object> map = mapper.readValue(url, Map.class);
 mapper.writeValue(new File("myfile.json"), map);

Ответ 7

Вот еще один способ сделать это с PHP и fOpen.

<?php
// Define your output file name and your search query
$output = 'result.txt';
$search = 'great';

write_twitter_to_file($output, $search);

/*
 * Writes Json responses from twitter API to a file output.
 * 
 * @param $output: The name of the file that contains the output 
 * @param $search: The search term query to use in the Twitter API
*/

function write_twitter_to_file($output, $search) {
    $search = urlencode($search);
    $url = 'http://search.twitter.com/search.json?q=' . $search;
    $handle = fopen($url, "r");

    if ($handle) {
        while (($buffer = fgets($handle, 4096)) !== false) {
            file_put_contents($output, $buffer, FILE_APPEND);
            echo "Output has been saved to file<br/>";
        }

        if (!feof($handle)) {
            echo "Error: unexpected fgets() fail\n";
        }

        fclose($handle);
    }

}
?>