Ruby JSON file operations

1. Parse json and symbolize keys

require "json"
def parse_json_with_symbolized_keys(filename)
  JSON.parse(File.read(filename), :symbolize_names => true)
end

E.g.

$ cat hi.json
{"hello":"world","ruby":["sinatra","rails"]}
[1] pry(main)> parse_json_with_symbolized_keys("hi.json")
=> {:hello=>"world", :ruby=>["sinatra", "rails"]}

2. Write a hash to a json file

require "json"

def write_hash_to_json_file(hash, filename)
   File.open(filename,"w") do |f|
     f.write(hash.to_json)
   end
end

E.g.

[9] pry(main)> hi = {:hello=>"world", :ruby=>["sinatra", "rails"]}
=> {:hello=>"world", :ruby=>["sinatra", "rails"]}
[10] pry(main)> write_hash_to_json_file(hi, "hello.json")
=> 44
$ cat hi.json
{"hello":"world","ruby":["sinatra","rails"]}

3. Now, I want a human readable json output file

require "json"

def write_hash_to_pretty_json_file(hash, filename)
   File.open(filename,"w") do |f|
     f.write(JSON.pretty_generate(hash))
   end
end

E.g.

[19] pry(main)> hi = {:hello=>"world", :ruby=>["sinatra", "rails"]}
=> {:hello=>"world", :ruby=>["sinatra", "rails"]}
[20] pry(main)> write_hash_to_pretty_json_file(hi, "pretty_hello.json")
=> 66

let us take a look at the output file:

$ cat pretty_hello.json
{
  "hello": "world",
  "ruby": [
    "sinatra",
    "rails"
  ]
}

Set the full width of separator in UITableView


cell.layoutMargins = UIEdgeInsetsZero
cell.preservesSuperviewLayoutMargins = false


tableView.separatorInset = UIEdgeInsetsZero

Ruby parses CSV file to an array of hash with symbolized keys

require "csv"

def parse_csv_return_array_of_hash(file_name)
  CSV.read(file_name, :headers => true, :header_converters => :symbol).collect do |row|
    row.to_hash
  end
end

For example, with the following input file:

year,month,date
2015,01,11
2016,01,12

it will return the following result:

[
  {:year=>"2015", :month=>"01", :date=>"11"},
  {:year=>"2016", :month=>"01", :date=>"12"}
]

A more detail explanation