I get the REST response data from a URL. I then write it to a JSON file, however, it's put it on one line in a long string, and I need to have it in readable format in the JSON file.
My code is:
require 'rubygems' require 'json' require 'rest-client' class Rest def self.getData response = RestClient.get 'http://jsonplaceholder.typicode.com/posts' response = JSON.parse(response) File.open('/Users/robertreed/RubymineProjects/draft/posts.json', 'w') do |f| f.write(response.to_json) end puts response end getData end It's printing to the console and writing to the JSON file on one line:
[{"userId"=>10, "id"=>100, "title"=>"at nam consequatur ea labore ea harum", "body"=>"cupiditate quo est a modi nesciunt}] Any suggestions on how I could achieve this?
getData, you should useget_data. In Ruby we use snake_case to name variables and methods. Instead ofopenandwritein a block, simply useFile.write('file.txt', response.to_json).File.write. Note: It's defined in IO but File inherits from IO, and you'll usually see it accessed from File.