How to convert a ruby hash object to JSON?
One of the numerous niceties of Ruby is the possibility to extend existing classes with your own methods. That's called "class reopening" or monkey-patching (the meaning of the latter can vary, though).
So, take a look here:
car = {:make => "bmw", :year => "2003"}
# => {:make=>"bmw", :year=>"2003"}
car.to_json
# NoMethodError: undefined method `to_json' for {:make=>"bmw", :year=>"2003"}:Hash
# from (irb):11
# from /usr/bin/irb:12:in `<main>'
require 'json'
# => true
car.to_json
# => "{"make":"bmw","year":"2003"}"
As you can see, requiring json
has magically brought method to_json
to our Hash
.
Converting an array of objects to JSON in Ruby
The code is converting array of strings (json string), not array of hashes.
Instead of using Person#to_json
in Directory#to_json
, use Person#to_hash
like following:
class Person
def to_hash
{
last_name: @last_name,
first_name: @first_name,
gender: @gender,
favorite_color: @favorite_color,
date_of_birth: @date_of_birth
}
end
def to_json
to_hash.to_json
end
end
class Directory
def to_json
@people.map do |person|
person.to_hash
end.to_json
end
end
How to convert a Ruby object to JSON from a File?
Look at the source. FileBlog is saying File.stat(@path).mode.to_s(8)
but @path
is an array. filePath
needs to be a path string, but ARGV is an array.
Perhaps you meant ARGV[0]
?
Convert a Ruby object to an IO-like object with a JSON
You could turn that hash into a JSON string and then make a StringIO out of it.
io = StringIO.new(JSON.generate(my_object))
method_that_accepts_io(io)
it looks like I could provide an IO-like object with the JSON instead of the JSON file directly as an argument.
Not sure what you meant by that, but if you have a file with JSON in it, and you can't pass just the filename (so the callee opens and reads it by itself), you can open the file and pass that.
io = File.open("my_file.json")
method_that_accepts_io(io)
I'm not even sure I quite understand what it refers to with the IO-like object.
This means an object that walks and quacks like IO (has methods #read
, #lines
, #bytes
and others)
Related Topics
Ruby: Creating a Sandboxed Eval
What Is the Best Practice When It Comes to Testing "Infinite Loops"
Ruby Block to String Instead of Executing
Detect If Application Was Started as Http Server or Not (Rake Task, Rconsole etc)
Dry Way to Assign Hash Values to an Object
Rails: Unable to Access Log File
Building Ruby with Rbenv and Ruby-Build Fails with Undefined Symbol: Sslv2_Method
How to Make 'Whenever' Gem Work on Windows
Removing a Model in Rails (Reverse of "Rails G Model Title...")
Format the Date Using Ruby on Rails
How Does Ruby's Sort_By {Rand} Work
Nested Forms in Rails - Accessing Attribute in Has_Many Relation
Test Output to Command Line with Rspec
How to Install Redcloth on Windows
What Does ::Myclass Ruby Scope Operator Do
Sass/Compass Compile into Many Locations
Rspec --Init Not Working/ 'Mkd Ir': Invalid Argument - ./C: (Errno::Einval)