How to write a JSON file in the correct format

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 am using Sinatra (I don’t know which version) and Ruby v 1.8.7.

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

+98
json ruby file
Mar 31 '11 at 23:15
source share
4 answers

Require 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 this:

 {"key_a":"val_a","key_b":"val_b"} 
+159
Mar 31 '11 at 23:18
source share

Formatted

 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 

Exit

 { "key_a":"val_a", "key_b":"val_b" } 
+77
May 04 '11 at 8:00
source share

This question refers to ruby ​​1.8, but it still stands at the top when searching.

in ruby> = 1.9 you can use

 File.write("public/temp.json",tempHash.to_json) 

besides what was 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 } 
+7
19 Oct '17 at 11:59 on
source share

To make this work on Ubuntu Linux:

  • I installed the ubuntu ruby-json package:

     apt-get install ruby-json 
  • I wrote a script in ${HOME}/rubybin/jsonDEMO

  • $HOME/.bashrc included:

     ${HOME}/rubybin:${PATH} 

(In this case, I also typed the above at the bash command line.)

Then it worked when I entered the command line:

 jsonDemo 
+3
Sep 04 '12 at 18:14
source share



All Articles