How to write to a JSON file in the correct format

dt1000 picture dt1000 · Apr 1, 2011 · Viewed 111.6k times · Source

I am creating a hash in Ruby and want to write it to a JSON file, in the correct format.

Here is my code:

tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
fJson = File.open("public/temp.json","w")
fJson.write(tempHash)
fJson.close

And here is the contents of the resulting file:

key_aval_akey_bval_b

I'm using Sinatra (don't know what version) and Ruby v 1.8.7.

How can I write this to the file in the correct JSON format?

Answer

Mike Lewis picture Mike Lewis · Apr 1, 2011

Require the JSON library, and use to_json.

require 'json'
tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
  f.write(tempHash.to_json)
end

Your temp.json file now looks like:

{"key_a":"val_a","key_b":"val_b"}