将URL输出的JSON保存到文件中

如何将URL输出的JSON保存到文件中?

例如来自Twitter搜索API(此http://search.twitter.com/search.json?q=hi )

语言并不重要。

编辑//我如何向EOF追加更新?

编辑2 //真的很棒的答案,但我接受了我认为最优雅的那个。

这在任何语言中都很容易,但机制各不相同。 使用wget和shell:

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

你可以使用CURL

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

这是(详细;))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) {} } 

另见

  • Java IO教程
  • Java URLConnection教程
  • 如何使用URLConnection

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

在shell中:

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

你可以使用jackson :

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

这是使用PHP和fOpen执行此操作的另一种方法。

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