How to Convert a Ruby Object to JSON

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



Leave a reply



Submit