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?

5
  • 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. Commented Apr 20, 2016 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). Commented Apr 20, 2016 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. Commented Apr 20, 2016 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? Commented Apr 20, 2016 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. Note: It's defined in IO but File inherits from IO, and you'll usually see it accessed from File. Commented Apr 20, 2016 at 23:21

1 Answer 1

2

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

See the pretty_generate documentation.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, this works nicely when puts to the console, however, how do I add this in when writing to JSON file? @JLB
f.write(JSON.pretty_generate(response))
@sammygadd I just did this, I forgot to add it, I now get `generate': only generation of JSON objects or arrays allowed (JSON::GeneratorError)
Never-mind Just solved the issue, Thanks a lot for the help.
I think I made the same mistake (calling .to_json on the response). @Speedychuck

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.