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?
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"}