Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

from json to a ruby hash?

Tags:

json

ruby

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 do i get it back again as my user_lib?

like image 306
beoliver Avatar asked Jan 29 '12 17:01

beoliver


People also ask

How do you turn JSON into a Ruby object?

The most simplest way to convert a json into a Ruby object is using JSON. parse and OpenStruct class. If there are more subsequence keys after the response , the object. response will returns another instance of the OpenStruct class holding the subsequence methods as those subsequence keys.

What does JSON do in Ruby?

Ruby Language JSON with Ruby Using JSON with Ruby JSON (JavaScript Object Notation) is a lightweight data interchange format. Many web applications use it to send and receive data. In Ruby you can simply work with JSON. At first you have to require 'json' , then you can parse a JSON string via the JSON.

What does JSON parse return in Ruby?

If you ever got annoyed by the fact that JSON. parse returns hash with string keys and prefer hashes with symbols as keys, this post is for you.


1 Answers

You want JSON.parse or JSON.load:

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

The key here is to use IO.read as a simple way to load the 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've linked to the JSON documentation above, so you should go read that for more details. But in summary:

  • json = my_object.to_json — method on the specific object to create a JSON string.
  • json = JSON.generate(my_object) — create JSON string from object.
  • JSON.dump(my_object, someIO) — create a JSON string and write to a 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.

Alternatively:

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

Note: I have used a "snake_case" name for the method corresponding to your "camelCase" saveUserLib as this is the Ruby convention.

like image 161
Phrogz Avatar answered Sep 17 '22 15:09

Phrogz