Speedychuck Speedychuck - 7 months ago 14
Ruby Question

Ruby API - JSON Parsing - Writing to file

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?

JLB JLB
Answer

Use pretty_generate, which will format the JSON in a more human-friendly format.

See the pretty_generate documentation.