Speedychuck Speedychuck - 2 years ago 173
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|

puts response



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?

Answer Source

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

See the pretty_generate documentation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download