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?
This question is for ruby 1.8 but it still comes on top when googling.
in ruby >= 1.9 you can use
File.write("public/temp.json",tempHash.to_json)
other than what mentioned in other answers, in ruby 1.8 you can also use one liner form
File.open("public/temp.json","w"){ |f| f.write tempHash.to_json }
With formatting
require 'json'
tempHash = {
"key_a" => "val_a",
"key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
f.write(JSON.pretty_generate(tempHash))
end
Output
{
"key_a":"val_a",
"key_b":"val_b"
}
To make this work on Ubuntu Linux:
I installed the Ubuntu package ruby-json:
apt-get install ruby-json
I wrote the script in ${HOME}/rubybin/jsonDEMO
$HOME/.bashrc
included:
${HOME}/rubybin:${PATH}
(On this occasion I also typed the above on the bash command line.)
Then it worked when I entered on the command line:
jsonDemo
Source: Stackoverflow.com