Ruby Objects and Json Serialization (Without Rails)

Ruby object to json (without rails)

instance_variables returns variables with the @ (which is arguably a bit silly), which you can just strip it with string splicing:

hash[var[1..-1]] = ...

Full example:

require 'json'

class Obj
attr_accessor :id, :status, :dateTime

def to_json
hash = {}
self.instance_variables.each do |var|
hash[var[1..-1]] = self.instance_variable_get var
end
hash.to_json
end
end

a = Obj.new
a.id = 42
a.status = 'new'

puts a.to_json

Gives:

{"id":42,"status":"new"}

Note that we don't strip the @ for instance_variable_get, as it's required here (which is arguably also a bit silly, but at least it's consistent).

Serialize Ruby object to JSON and back?

The easiest way is to make a to_json method and a json_create method. In your case, you can do this:

class CrawlStep
# Insert your code here (attr_accessor and initialize)

def self.json_create(o)
new(*o['data'])
end

def to_json(*a)
{ 'json_class' => self.class.name, 'data' => [id, name, next_step] }.to_json(*a)
end
end

Then you serialize by calling JSON.dump(obj) and unserialize with JSON.parse(obj). The data part of the hash in to_json can be anything, but I like keeping it to the parameters that new/initialize will get. If there's something else you need to save, you should put it in here and somehow parse it out and set it in json_create.

How to save data into JSON with Ruby and use it later?

You Need to Serialize to JSON First

You are currently writing native Ruby objects to your file, not JSON. To serialize an object to JSON, you need to call a method like #to_json on it after requiring the JSON module.

For example, using Ruby 3.0.3:

require 'json'

books = [{"Title"=>"My title", "Author"=>"My author"}]
File.open("books.json", "w") { |f| f.puts books.to_json }

will write the expected JSON object of [{"Title":"My title","Author":"My author"}] to your file and then close itself.

If you want, you can validate that this worked in Ruby, or at the command line with jq. As a command-line example:

jq . books.json 
[
{
"Title": "My title",
"Author": "My author"
}
]

There are certainly other ways to generate JSON objects in various formats for serialization, but that's the missing piece in your code. You have to convert your Ruby objects to JSON objects before writing them out to the file, or (in your case) you just end up writing the implicit #to_str value of the object instead.



Related Topics



Leave a reply



Submit