From json to ruby โ€‹โ€‹hash?

I can go one way using

require 'json' def saveUserLib(user_lib) File.open("/Users/name/Documents/user_lib.json","w") do |f| f.write($user_lib.to_json) end end uname = gets.chomp $user_lib["_uname"] = uname saveUserLib($user_lib) 

but how can I return it again as user_lib?

+46
json ruby
Jan 29 '12 at 17:21
source share
3 answers

Do you want JSON.parse or JSON.load

 def load_user_lib( filename ) JSON.parse( IO.read(filename) ) end 

The key point here is to use IO.read as an easy way to load a JSON string from disk so that it can be parsed. Or, if you have UTF-8 data in your file:

  my_object = JSON.parse( IO.read(filename, encoding:'utf-8') ) 

I contacted the JSON documentation above, so you should read this for more details. But in general:

  • json = my_object.to_json - a method for a specific object to create a JSON string.
  • json = JSON.generate(my_object) - create a JSON string from an object.
  • JSON.dump(my_object, someIO) - create a JSON string and write to the file.
  • my_object = JSON.parse(json) - create a Ruby object from a JSON string.
  • my_object = JSON.load(someIO) - create a Ruby object from a file.

As an alternative:

 def load_user_lib( filename ) File.open( filename, "r" ) do |f| JSON.load( f ) end end 

Note. I used the name "snake_case" for the method that matches your "camelCase" saveUserLib , since this is a Ruby convention.

+96
Jan 29 '12 at 17:29
source share

here is an example:

 require 'json' source_hash = {s: 12, f: 43} json_string = JSON.generate source_hash back_to_hash = JSON.parse json_string 
+2
Jan 29 '12 at 17:26
source share

JSON.load will do the trick. Here is an example that goes both ways:

 >> require 'json' => true >> a = {"1" => "2"} => {"1"=>"2"} >> b = JSON.dump(a) => "{\"1\":\"2\"}" >> c = JSON.load(b) => {"1"=>"2"} 
+2
Jan 29 '12 at 17:28
source share



All Articles