4

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?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Speedychuck
  • 400
  • 9
  • 29
  • If you're saving the JSON in "pretty format", to allow humans to edit it, you should instead use YAML. It's much more readable. JSON is great when transferring data between apps, but formatting it for readability can really increase the file size, causing it to use more CPU, more network bandwidth and app time. – the Tin Man Apr 20 '16 at 22:35
  • Don't name a class "Rest". "RestResponse" would be better since classes should be "things". Instead of `getData`, you should use `get_data`. In Ruby we use snake_case to name variables and methods. Instead of `open` and `write` in a block, simply use `File.write('file.txt', response.to_json)`. – the Tin Man Apr 20 '16 at 22:41
  • That sounds like a good piece of advice, I am not really sure what I'll be using JSON for just joined a new QA team and I've only used xml to hold parameters in the passed. But got told to look into it. – Speedychuck Apr 20 '16 at 22:42
  • Thanks for the pointers on class names and snake_case I will adjust myself accordingly, however, is it not good to use blocks for breakdown of code? As in keeping the code organised? – Speedychuck Apr 20 '16 at 22:48
  • Blocks are useful for that, but you're wasting code to do something very simple. You're basically doing a write, so just do that using [`File.write`](http://ruby-doc.org/core-2.3.0/IO.html#method-c-write). _Note:_ It's defined in IO but File inherits from IO, and you'll usually see it accessed from File. – the Tin Man Apr 20 '16 at 23:21

1 Answers1

2

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

See the pretty_generate documentation.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
JLB
  • 323
  • 3
  • 8